Home > Mobile >  Conditional routing in Angular
Conditional routing in Angular

Time:02-14

I have a route:

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

And I'm developing a new component that will replace the BusinessRulesComponent at some point. Users can opt in to the new NewBusinessRulesComponent by using a feature flag.

Now I'm wondering if it's possible to do conditional routing based on the selected feature flag.

I've added a guard CanAccessNewBusinessRules but as far as I know this can only stop a route from showing up:

    {
        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;

Can I change the routing in the guard, or is it better to add another route that's only active when the flag is enabled?

CodePudding user response:

No. you can't do it. A good way to handle situations like this is to return UrlTree from your guard so angular can route to another route.

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),
  }

and then in your guard decide that first route(page) can activate or you need to navigate to page2

profile.gurad.ts

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