【问题标题】:Angular Router don't cancel navigation on blocked routeAngular Router 不会取消阻塞路线上的导航
【发布时间】:2020-05-03 06:41:16
【问题描述】:

我目前为我的 Angular 应用准备了这些 routes

const routes: Routes = [
  { path: '', component: DashboardComponent },
  { path: 'login', component: LoginComponent },
  { path: 'upload', component: UploadPictureComponent, canActivate: [AngularFireAuthGuard] },
  { path: 'view', component: ListPictureComponent, canActivate: [AngularFireAuthGuard] },
  { path: '**', component: NotFoundComponent },
];

当前行为: 如果用户未登录并转到路由uploadview,他们的路由将被阻止并且不会看到任何内容。

期望的行为: 如果用户转到任何被阻止的路线,我想向他们显示NotFoundComponent

我无法解决的问题是,当路由被守卫拒绝时,Angular 会取消路由事件。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我将此答案作为可能的解决方案之一,我不知道它是最好的还是最佳做法。

    1. 我会保留一个常量字符串,用于所有手动后备路径导航。也许是这样的: const FALLBACK_PATH = '未找到'。我会将它保存在一个共享位置,我可以在我想要的任何组件中使用它。

    2. AngularFireAuthGuard守卫中,当登录条件失败时,我会这样做:

       this.router.navigateByUrl(FALLBACK_PATH, { skipLocationChange: true });
       return false;
      

      注意:我正在做skipLocationChange,因为我不希望错误的路径显示在 URL 中,你可以拥有它,也可以不拥有它,取决于你的要求。 另外,上面的代码没有经过测试,只是给你一个方法。

    【讨论】:

      【解决方案2】:

      canActivate 目前可以返回所需的 URLTree。您可以测试已登录的用户并在AngularFireAuthGuard 中重定向他:

      constructor(private _authService: AuthService, private _router: Router){}
      canActivate(
          next: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<boolean | UrlTree> | boolean | UrlTree 
      {
          if(this._authService.isLoggedIn) {
            // runs your current authorization logic
          } else {
            // the argument of parse is any string that doesn't represent
            // a real route
            return this._router.parse('go-to-page-not-found');
          }
        }
      

      【讨论】:

        【解决方案3】:

        如果canActivate返回false,您必须手动重定向到“NotFoundComponent”

          canActivate(): boolean {
            if (!this.auth.isAuthenticated()) {
              this.router.navigate(['login']);
              return false;
            }
            return true;
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-19
          • 1970-01-01
          • 1970-01-01
          • 2022-06-15
          • 2016-06-28
          • 1970-01-01
          • 2017-12-11
          相关资源
          最近更新 更多