Monday, 8 June 2020

angular 8/9 import vs declaration vs providers, and for services use injectable{providedIn} instead of putting in providers

  • imports makes the exported declarations of other modules available in the current module
  • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
  • providers are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.

@Injectable({
  providedIn: 'root',
})
What exactly does providedIn do? 

if you use providedIn, the injectable is registered as a provider of the Module without adding it to the providers of the module.
From Docs
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.

https://stackoverflow.com/questions/50848357/what-is-the-purpose-of-providedin-with-the-injectable-decorator-when-generating
https://stackoverflow.com/questions/39062930/what-is-the-difference-between-declarations-providers-and-import-in-ngmodule 

No comments:

Post a Comment