Redirect to a different component inside @CanActivate in Angular2

前端 未结 6 598
攒了一身酷
攒了一身酷 2020-12-03 10:03

Is there any way we can redirect to a different component from @CanActivate in Angular2 ?

6条回答
  •  余生分开走
    2020-12-03 10:28

    If you are using an observable to determine, you can leverage tap operator from rxjs:

    @Injectable({
      providedIn: SharedModule // or whatever is the equivalent in your app
    })
    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService,
                  private router: Router) {}
    
      canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
        return this.authService.isLoggedIn()
          .pipe(tap((isLoggedIn: boolean) => {
            if (!isLoggedIn) {
              this.router.navigate(['/']);
            }
          }));
      }
    
    }
    

提交回复
热议问题