【发布时间】:2017-06-09 04:14:34
【问题描述】:
如果用户未登录,我有一个 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/#/。 怎么了?
【问题讨论】:
-
那么你在日志中看到“响应OK”了吗?
-
是的,响应正常
-
不,我的意思是你的代码中有一个
console.log("response OK");。你在控制台日志中看到了吗? -
我收到两个响应都OK,并且“响应OK”显示在日志中,因此到达了那部分代码
标签: angular routing angular-routing