问题描述
我有一个实现 CanActivate 的 AuthGuard (用于路由).
I have an AuthGuard (used for routing) that implements CanActivate.
canActivate() {
return this.loginService.isLoggedIn();
}
我的问题是,CanActivate-result取决于http-get-result- LoginService 返回一个 Observable .
My problem is, that the CanActivate-result depends on a http-get-result - the LoginService returns an Observable.
isLoggedIn():Observable<boolean> {
return this.http.get(ApiResources.LOGON).map(response => response.ok);
}
我如何将它们结合在一起-使CanActivate依赖于后端状态?
How can i bring those together - make CanActivate depend on a backend state?
请注意,这个问题是从2016年开始的-角/路由器的使用非常早期.
Please note, that this question is from 2016 - a very early stage of angular/router has been used.
推荐答案
您应将"@ angular/router"升级到最新版本.例如"3.0.0-alpha.8"
You should upgrade "@angular/router" to the latest . e.g."3.0.0-alpha.8"
修改AuthGuard.ts
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private loginService:LoginService, private router:Router) { }
canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot) {
return this.loginService.isLoggedIn().map(e => {
if (e) {
return true;
}
}).catch(() => {
this.router.navigate(['/login']);
return Observable.of(false);
});
}
}
如有任何疑问,请问我!
If you have any questions, ask me!
这篇关于Angular 2-路由-CanActivate与Observable一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!