I am working on Angular 8.2.5 and I am trying to pass route data by calling a service. I have a lazy loaded module that I want to import it in several other modules. I will pass a PermissionHandlerModule service which will contain each parent module permissions:
@NgModule({
imports: [
RouterModule.forChild([
{
path: '',
canActivate: [AppRouteGuard],
canActivateChild: [AppRouteGuard],
children: [
{
path: 'route1',
component: Component1,
//data: { permission: 'MyModulePermissionsForRoute1' },
data: { permission: IPermissionHandler.route1Permission },
},
{
path: 'route2',
component: Component12,
data: { permission: IPermissionHandler.route1Permission },
},
]
}
])
],
exports: [
RouterModule
]
})
@Injectable()
export abstract class IPermissionHandler {
abstract route1Permission: string;
abstract route2Permission: string;
}
@Injectable()
export class PermissionHandlerModuleA implements IPermissionHandler {
route1Permission: string = 'ModuleARoute1Permission';
route2Permission: string = 'ModuleARoute2Permission';
}
@Injectable()
export class PermissionHandlerModuleB implements IPermissionHandler {
route1Permission: string = 'ModuleBRoute1Permission';
route2Permission: string = 'ModuleBRoute2Permission';
}
// Module A imports section
{ provide: PermissionHandlerModuleA, useClass: IPermissionHandler}
// Module B imports section
{ provide: PermissionHandlerModuleB, useClass: IPermissionHandler}
How can I achieve something like the above?
You could use an injection token for something like this.
And then the token:
Now say you have two services implementing
IPermissionHandler
namelyPermissionHandler1
andPermissionHandler2
which are in two different modules. Say for the first module, you want to usePermissionHandler1
then you need to provide in this way:In another module you can use:
Then, wherever you want to use the service, you can inject in this way: