With modules, we've defined providers in the module and those would get registered on the module level.
If I understand correctly, the way to organize DI/providers with standalone components is by using providers in route definitions.
So, if we previously had a module that loaded under the route /moduleA and module itself had different services registered in providers, then with the new approach we would have same array of providers defined for the route /moduleA and all its children routes.
Is that correct statement?
And, if that's true, when to put providers into some route definition and when to standalone component providers array?
You're correct. You can still provide:
root (think HttpClient)@Injectable({
providedIn: 'root'
})
export class MyService {}
NgModule.providers (shared state by module)@NgModule({
declarations: [SomeComponentThatDependsOnMyService],
providers: [MyService]
})
export class MyFeatureModule {}
Route.providers (shared state by route)const featureRoutes = [
{
path: '',
children: [
{ path: 'a', loadComponent: () => import('./a.component.ts').then(c => c.AComponent) },
{ path: 'b', loadComponent: () => import('./b.component.ts').then(c => c.BComponent) },
],
providers: [MyService]
},
] as Routes;
const appRoutes = [
{
path: 'feature',
loadChildren: () => featureRoutes,
providers: [MyOtherService]
},
{ path: '**', component: NonFeatureComponent },
] as Routes;
bootstrapApplication(App, {
providers: [
provideRouter(appRoutes)
]
});
Component.providers (think instance state)@Component({
selector: 'app-isolated',
standalone: true,
providers: [MyService]
})
export class MyIsolatedComponent {}
There is a hierarchy to where these services are provided and the "correct" place to provide a given service depends on factors including:
But using @Injectable({ providedIn: 'root' }) is still the preferred method of providing a service because it allows for tree shaking services that are not used. I'd wager that what you're suggesting, Route.providers in a lazy-loaded route (loadComponent() or loadChildren(Routes)), is the second preference but the documentation does not make that explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With