Angular2 route guard returning Observable, how to handle errors

前端 未结 1 1376
名媛妹妹
名媛妹妹 2021-01-05 03:19

I have a route guard like below

@Injectable()
export class AuthGuard implements CanActivate {

constructor(private router: Router, private authenticationSvc:         


        
相关标签:
1条回答
  • 2021-01-05 03:36

    You can catch errors and return Observable<bool> as follows:

    @Injectable()
    export class AuthGuard implements CanActivate {
    
    constructor(private router: Router, private authenticationSvc: AuthenticationService) { }
    
    canActivate(): Observable<boolean> {
        return this.authenticationSvc.getAuthenticatedUser().map(
            r => {
                if (this.authenticationSvc.isAuthenticated()) {
                    // logged in so return true
                    return true;
                }
                this.router.navigateByUrl('/login');
                return false;
            })
            .catch((error: any) => {
                this.router.navigateByUrl('/login');
                return Observable.of(false);
            });
    }
    
    0 讨论(0)
提交回复
热议问题