Angular 2 - Routing - CanActivate work with Observable

前端 未结 7 1036
终归单人心
终归单人心 2020-11-30 18:30

I have an AuthGuard (used for routing) that implements CanActivate.

canActivate() {
    return this.loginService.isLoggedIn         


        
7条回答
  •  独厮守ぢ
    2020-11-30 18:51

    Updating Kery Hu's answer for Angular 5+ and RxJS 5.5 where the catch operator is deprecated. You should now use the catchError operator in conjunction with pipe and lettable operators.

    import { Injectable } from '@angular/core';
    import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { catchError, map} from 'rxjs/operators';
    import { of } from 'rxjs/observable/of';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private loginService: LoginService, private router: Router) { }
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable  {
        return this.loginService.isLoggedIn().pipe(
          map(e => {
            if (e) {
              return true;
            } else {
              ...
            }
          }),
          catchError((err) => {
            this.router.navigate(['/login']);
            return of(false);
          })
        );
      }   
      
    }
    

提交回复
热议问题