angular 2 - 路由守卫返回 observable<boolean>,理解

angular 2 - routing guard returning observable<boolean>, understanding

我想这可能更像是一个 rxjs 理解主题,但上下文最能说明我对它的需求:)

下面是我的 PageGuard class 中的工作代码,它会阻止路由到页面,除非 localStorage 中存在有效的 jwt。

CheckForToken() 仅附加授权 Header 如果本地存储中存在令牌。

public isAuthenticated():Observable<boolean>{
    this.checkForToken();
    let isAuth = new Observable<boolean>(observer => {
        this.http.get(`https://testhan-api.selfbits.io/api/v1/user`,{headers: this.headers}).subscribe(res => {
            if (res.status === 200){
                observer.next(true);
                observer.complete();
            }else{
                observer.next(false);
                observer.complete()
            }
        },err => console.log(err));
    });
    return isAuth
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.isAuthenticated()
}

路由路径如下所示

{ 
    path:'dashboard', 
    component:DashboardComponent, 
    canActivate:PageGuard
}

我的问题:到目前为止,我的理解是您需要订阅一个可观察对象才能执行它,例如

observable.subscribe(res => //do something with res)

但这里我只返回一个 observable,它没有被订阅,但是守卫如何评估它?

感谢您的澄清!

如果你真的想深入了解细节......这里是:-)

关于导航的大部分工作都在 runNavigate method. The point where it gets to the guards is here, where there's a call to checkGuards which returns an Observable<boolean>. Depending on what type of guard it is, it will call a specific method for that type of guard, that also returns an Observable<boolean>. All of those "specific methods" call a method wrapIntoObservable 传递 guard 方法的结果。如果您查看 wrapIntoObservable 源代码,您会看到它检查 Observable、Promise 或常规值。无论哪种情况,Observable 总是 returned.

现在回到调用堆栈,一旦所有守卫 Observable 都合并到一个发出单个布尔值的 Observable 中,该 observable 就会经历 resolving data for the routes 的过程。如果合并后的 guard observable return 为 false,则新的 resolve Observable 将 return 为 false 的 Observable。否则它将 return 解析数据的 Observable。

在下一步中,解析 Observable 得到 subscribed to with forEach. If the resolved data is false (false forwarded from the guards), then it will return nothing and the routing stops. Otherwise, anActivatedRoute。从那里继续导航的其余部分。