What is the purpose of providedIn with the Injectable decorator when generating Services in Angular 6?

Stefan Zvonar picture Stefan Zvonar · Jun 14, 2018 · Viewed 45.4k times · Source

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.

@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?

UPDATE:

For anyone else, the following paragraph provided another good explanation of it also, in particular if you want to provide your service to only a feature module.

There is now a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module." - https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/

UPDATE 2:

After further investigation, I have decided it is only useful to have providedIn: 'root'

If you want to provide a service in any module other than the root module, then you are better off using the providers array in the feature module's decorators, otherwise you will be plagued with circular dependencies. Interesting discussions to be had here - https://github.com/angular/angular-cli/issues/10170

Answer

Sajeetharan picture Sajeetharan · Jun 14, 2018

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.