35

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

4

6 回答 6

64

到今天为止,使用最新的@angular/router 3.0.0-rc.1,这里有一些关于如何通过CanActivate路由守卫来做到这一点的参考资料:

  1. 角度 2 参考
  2. Nilz11Jason对这个 SO 问题的两个答案

逻辑的主要要点如下:

// ...
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (this.authService.isLoggedIn) {
    // all ok, proceed navigation to routed component
    return true;
  }
  else {
    // start a new navigation to redirect to login page
    this.router.navigate(['/login']);
    // abort current navigation
    return false;
  }
}
于 2016-08-26T09:08:24.857 回答
13

你的后卫可以很容易地成为一个注射剂,因此,它可以包括它自己的注射剂。所以我们可以简单地注入路由器,以便重定向。不要忘记在您的应用模块中添加服务作为提供程序。

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (!authService.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

export const ROUTES: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'protected', loadChildren: 'DashboardComponent', canActivate: [AuthGuard]}
];
于 2016-10-14T15:27:56.523 回答
12

是的你可以!这样做会阻止你的组件实例化。

首先,新建一个文件src/app-injector.ts

let appInjectorRef;

export const appInjector:any = (injector = false) => {
    if (!injector) {
        return appInjectorRef;
    }

    appInjectorRef = injector;

    return appInjectorRef;
};

然后,从bootstrap

// ...
import {appInjector} from './app-injector';
// ...


bootstrap(App, [
  ROUTER_PROVIDERS
]).then((appRef) => appInjector(appRef.injector));

最后在你的功能

// ...
import {appInjector} from './app-injector';
// ...

@CanActivate((next, prev) => {
  let injector = appInjector();
  let router = injector.get(Router);

  if (42 != 4 + 2) {
    router.navigate(['You', 'Shall', 'Not', 'Pass']);
    return false;
  }

  return true;
})

等等瞧!

在这里讨论过https://github.com/angular/angular/issues/4112

你可以在这里找到一个完整的例子http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts

于 2016-01-28T14:58:49.920 回答
3

从 Angular 7.1 开始,您可以返回UrlTree而不是boolean

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(): boolean | UrlTree {
    return this.authService.isAuthenticated() || this.router.createUrlTree(['/login']);
  }
}
于 2019-03-27T20:22:03.827 回答
2

这可能会帮助那些试图在继续之前等待某事的人。

waitForBonusToLoad(): Observable<[boolean, string]> {

const userClassBonusLoaded$ = this.store.select(fromRoot.getUserClasssBonusLoaded);
const userClassSelected$ = this.store.select(fromRoot.getClassAttendancesSelectedId);

return userClassBonusLoaded$.withLatestFrom(userClassSelected$)
  .do(([val, val2]) => {
    if (val === null && val2 !== null) {
      this.store.dispatch(new userClassBonus.LoadAction(val2));
    }
  })
  .filter(([val, val2]) => {
    if(val === null && val2 === null) return true;
    else return val;
  })
  .map(val => {
    return val;
  })
  .take(1);
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.waitForBonusToLoad().map(([val, val2]) =>
  {
    if(val === null && val2 === null){
      this.router.navigate(['/portal/user-bio']);
      return false;
    }
    else {
      return true;
    }
  }
)
}
于 2017-02-08T16:35:28.180 回答
1

如果您使用 observable 来确定,您可以利用tapoperator 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<boolean> {
    return this.authService.isLoggedIn()
      .pipe(tap((isLoggedIn: boolean) => {
        if (!isLoggedIn) {
          this.router.navigate(['/']);
        }
      }));
  }

}
于 2018-07-08T20:22:28.827 回答