patterntypescriptangularMajor
What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?
Viewed 0 times
angularwithprovidedingeneratingservicestheinjectablepurposedecoratorwhen
Problem
When generating services in the Angular CLI, it is adding extra metadata with a 'provided in' property with a default of 'root' for the Injectable decorator.
What exactly does providedIn do? I am assuming this is making the service available like a 'global' type singleton service for the whole application, however, wouldn't be cleaner to declare such services in the provider array of the AppModule?
@Injectable({
providedIn: 'root',
})What exactly does providedIn do? I am assuming this is making the service available like a 'global' type singleton service for the whole application, however, wouldn't be cleaner to declare such services in the provider array of the AppModule?
Solution
if you use providedIn, the injectable is registered as a provider of the Module without adding it to the providers of the module.
From
The service itself is a class that the CLI generated and that's
decorated with @Injectable. By default, this decorator is configured
with a providedIn property, which creates a provider for the service.
In this case, providedIn: 'root' specifies that the service should be
provided in the root injector.
From
DocsThe service itself is a class that the CLI generated and that's
decorated with @Injectable. By default, this decorator is configured
with a providedIn property, which creates a provider for the service.
In this case, providedIn: 'root' specifies that the service should be
provided in the root injector.
Context
Stack Overflow Q#50848357, score: 75
Revisions (0)
No revisions yet.