Angular 2 - Routing - CanActivate 与 Observable 一起工作 [英] Angular 2 - Routing - CanActivate work with Observable
本文介绍了Angular 2 - Routing - CanActivate 与 Observable 一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实现 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 年 - 角度/路由器的早期阶段已被使用.
推荐答案
你应该升级@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 - Routing - CanActivate 与 Observable 一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文