Angular 4 CanActivate防护装置不加载与服务一起使用的组件;简单的Observable.of(true)有效

时间:2017-09-19 16:19:34

标签: node.js angular typescript angular-services angular-components

我试图在Angular中使用CanActivate后卫,当我从中调用服务时return true甚至return Observable.of(true);

但是当我不调用任何服务并且只是写时,它工作并加载组件 Observable.of(true);

中的canActivate

以下是代码doenst work:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    //return Observable.of(true);
    return this._userService.verify().subscribe((result: Array<Object>) => {
        let user : UserDetail = new UserDetail();
        Object.keys(user).forEach(key=>{
             let listValue = result.filter(m=>m["m_type"]==key);
             if(listValue.length>0){
                user[key] =  result.filter(m=>m["m_type"]==key)[0]["m_value"];
             }
        });
        this.userDetails = user;
        return Observable.of(true);
        //return true;
    }, (error: any) => {
        // error when verify so redirect to login page with the return url
        this._router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return true;
    }, () => {
        console.log("auth.guard : completed.");
        //return true;
        return Observable.of(true);
    });

以下代码有效:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

            return Observable.of(true);
        });

1 个答案:

答案 0 :(得分:2)

Observable不承诺订阅中的任何返回代码都不起作用。将代码更改为此。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
//return Observable.of(true);
return this._userService.verify().switchMap((result: Array<Object>) => {
    let user : UserDetail = new UserDetail();
    Object.keys(user).forEach(key=>{
         let listValue = result.filter(m=>m["m_type"]==key);
         if(listValue.length>0){
            user[key] =  result.filter(m=>m["m_type"]==key)[0]["m_value"];
         }
    });
    this.userDetails = user;
    return Observable.of(true);
    //return true;
}).catch(() => {

    // error when verify so redirect to login page with the return url
    this._router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return Observable.of(false);


});

当你let x = this.observable.subscribe();时 x是订阅但不可观察。