Home > Mobile >  Change angular router component depends on configuration
Change angular router component depends on configuration

Time:05-09

I have the next routing definition:

export const ROUTES: Routes = [
  {
    path: "test",
    component: FooComponent 
]

in a my application I have two components: FooComponent and BarComponent, these components should be under one route test, but it depends on configuration parameter, which I load from a server. Is it possible somehow to draw routing, or replace component depends on my configuration?

 param: "foo" // or "bar"

I tried guard approach, but looks like it is not the best way to do this.

CodePudding user response:

Netanel Basal has an article on configuring routing based on external data. It should work for your scenario, although you may need to use separate modules for the components to match his approach exactly.

In the comments of the article he says it will work with async service call too, if you chain a Promise

import { RouterModule, ROUTES, Routes } from '@angular/router';
import { FeatureFlagService } from './feature-flag.service';

 function routesFactory(ffService: FeatureFlagService) {
   return [
    {
      path: 'todos',
      loadChildren: () => {
        return ffService.hasPermssion('todosV2') ? 
            import('./todos-v2/todos-v2.module').then(m => m.TodosV2Module) : 
            import('./todos/todos.module').then(m => m.TodosModule);
      }
    }]
 }

@NgModule({
  imports: [RouterModule.forRoot([])],
  providers: [{
    provide: ROUTES,
    useFactory: routesFactory,
    multi: true,
    deps: [FeatureFlagService]
  }],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

CodePudding user response:

The below may be helpful.

You can pass parameters to routes e.g. as 'myType' in below snap.

{path: 'test/:myType', component: TestComponent},
{path: 'gotoFoo', component: FooComponent},
{path: 'gotoBar', component: BarComponent}

In TestComponent you can fetch the param value and based on the value, navigate to the desired path.

currentType = this.myAciveRoute.snapshot.params['myType'];
if(currentType == 'foo' ){
  this.myAciveRoute.navigate(['/gotoFoo']);
}
if(currentType == 'bar' ){
  this.myAciveRoute.navigate(['/gotoBar']);
}
  • Related