Angular2 Authguard重定向路由不起作用

时间:2016-12-21 20:05:23

标签: angular routes

我创建了一个authguard来防止未登录的用户进入页面。 authguard运行并返回true后,它不会重定向到相应的页面。我做错了吗?

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
                private authStatusService: AuthStatusService,
                private authService: AuthService,
                private router: Router ) { }

    canActivate(): any {

        return this.authStatusService.authStatus.subscribe(i => {
            if(i === 'auth-login-success') {
                return Observable.fromPromise(this.authService.getUser())
                    .subscribe(res => {
                        if(!res.id) {
                            this.router.navigate(['summary']);
                            return Observable.of(false);
                        }
                        return Observable.of(true);
                    },
                    error => {
                        return Observable.of(false);
                    })
            } else {
                console.log('user has not logged in')
                this.router.navigate(['login']);
                return Observable.of(false);
            }
        })
    }
}

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
                private authStatusService: AuthStatusService,
                private authService: AuthService,
                private router: Router ) { }

    canActivate(): any {

        return this.authStatusService.authStatus
        .mergeMap(i => {
            if(i === 'auth-login-success') {
                return this.authService.getUser())
                    .map(res => {
                        if(!res.id) {
                            this.router.navigate(['summary']);
                            false;
                        }
                        return true;
                    })
                    .catch(error => {
                        return false;
                    })
            } else {
                console.log('user has not logged in')
                this.router.navigate(['login']);
                return false;
            }
        })
        .first() // not sure if this line is still necessary
    }
}

路由器需要booleanPromise<boolean>Observable<boolean>。 当您致电subscribe()时,您会得到Subscription,但却无法工作。 使用map()会返回Observable