我有一个Angular2应用程序,如果用户未登录,则应该阻止前往某个页面。这是我的app.routes文件:
export const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: '**', component: LoginComponent },
];
以及我的 AuthGuard 文件
@Injectable()
export class AuthGuard implements CanActivate {
response: ResponseInterface;
constructor(private router: Router, private localStorage: LocalStorageService,
private services: MyService) { }
canActivate() {
let token = String(this.localStorage.get('token'));
if (token != null) {
this.services.keepAlive(token).subscribe(
response => this.response = response,
error => alert(error),
() => {
if (this.response.status == 'OK') {
console.log("response OK");
return true;
} else {
console.log("response KO");
this.router.navigate(['/login']);
return false;
}
}
)
} else {
this.router.navigate(['/login']);
return false;
}
现在,如果我尝试导航到http://localhost:4200/#/home路径并且我已经有一个令牌存储在localStorage中,什么也不会发生:主页没有显示,导航栏上的路径变为http://localhost:4200/#/。出了什么问题?
console.log("response OK");
。你在控制台日志中看到它了吗? - eko