Angular 中的条件路由

Conditional routing in Angular

我有一条路线:

    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
    },

而且我正在开发一个新组件,它将在某个时候取代 BusinessRulesComponent。用户可以使用功能标记选择加入新的 NewBusinessRulesComponent

现在我想知道是否可以根据所选功能标志进行条件路由。

我添加了一个守卫 CanAccessNewBusinessRules 但据我所知,这只能阻止一条路线出现:

    {
        path: 'business-rules',
        data: { routeName: _('Business rules') },
        component: BusinessRulesComponent,
        canActivate: [CanAccessNewBusinessRules]
    },

CanAccessNewBusinessRules:

        const new_business_rules_flagged = await this.companyFeatureFlagsService.getAllFeatureFlags(company.id)
            .then((flags) => flags.includes(possibleFlags.new_business_rules))

        if (new_business_rules_flagged) {
            // this.router.navigate(['new-business-rules'])
            return false;
        }

        return true;

我可以更改守卫中的路由,还是添加另一条仅在启用标志时才有效的路由更好?

没有。你做不到。处理这种情况的一个好方法是 return UrlTree 从你的后卫那里 angular 可以路由到另一条路线。

app-routing.module.ts

  {
    path: 'page',
    loadChildren: () => import('./pages/home/home.module').then(m => m.HomeModule),
    canActivate: [ProfileGuard]
  },
  {
    path: 'page2',
    loadChildren: () => import('./pages/another/another.module').then(m => m.AnotherModule),
  }

然后在你的警卫中决定第一条路线(page)可以激活或者你需要导航到 page2

profile.gurad.ts

 if (!condition) {
   return this.router.parseUrl('/page2');
 }
 return true;