我有一个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 /#/.怎么了?
canActive
方法应返回Observable
,Promise
或boolean
.
您正在订阅this.services.keepAlive
Observable,并将boolean
值返回到subscribe回调,而不是将其返回给canActivate
方法.更改您的代码如下:
canActivate(): Observable| Promise | boolean { let token = String(this.localStorage.get('token')); if (token != null) { return this.services.keepAlive(token) .map(response => { if (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; } }
这样,布尔类型(Observable
)的Observable 将返回给canActive
方法,并且路由解析应该按预期工作.