Search code examples
angulardependency-injectionproviderinjection-tokens

Angular use different injection token conditionally in module from routing module


I want to use different value for a injection token in a module conditionally, something like:

  providers: [
    {
      provide: ABC_TOKEN,
      useValue: useA ? a : b,
    },
  ],

how to do that? and also I want to pass the useA from a routing module which maybe something like:

      {
        path: 'abc',
        loadChildren: () =>
          import('../abc.module').then(
            (m) => m.AbcModule,
          ),
        data: {
          useA: true,
        },
      },

So what I want is based on the data in the routing module, I want to use different value of injection token for the module

Thanks.


Solution

  • If you wanted to decide the value of ABC_TOKEN injection token, consider using useFactory function. And define that in your AbcModule module.

    providers: [
       {
          provide: ABC_TOKEN,
          useFactory: (route: ActivatedRoute) => {
            // below can be improved. 
            let useA = route.firstChild.firstChild.snapshot.data['useA'];
            return route.data['useA'] ? a : b;
          },
          deps: [ActivatedRoute],
       },
    ],
    

    On catch is, you have to access the parent route data from the current activatedRoute. For that, you may have to traverse. or two steps back using route.firstChild.firstChild.snapshot.data['useA']. Also, this can be written using a recursive function.

    I've created a Demo for you on this. Navigate to the product-list page and check code inside ProductModule

    Stackblitz