Issue
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?
Solution
You're correct. You can still provide:
- Services needed by your whole app in
root
(thinkHttpClient
)
@Injectable({
providedIn: 'root'
})
export class MyService {}
- Services needed by a group of components in
NgModule.providers
(shared state by module)
@NgModule({
declarations: [SomeComponentThatDependsOnMyService],
providers: [MyService]
})
export class MyFeatureModule {}
- Services needed by a group of components in
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)
]
});
- Services needed by a single component in
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:
- How many components or other services need to share the same instance of your service
- How many components or other services should even know about your service
- When your service should actually be instantiated (is it needed at application startup or only after a certain route/component has been loaded?)
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.
Answered By - D M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.