angular 6 dependency injection angular 6 dependency injection javascript javascript

angular 6 dependency injection


Basically you can use either, But as per new CLI provideIn will be automatically added while creating service

#providedIn

There is now a new, recommended, way to register a provider, directlyinside the @Injectable() decorator, using the new providedInattribute. It accepts 'root' as a value or any module of yourapplication. When you use 'root', your injectable will be registeredas a singleton in the application, and you don’t need to add it to theproviders of the root module. Similarly, if you use providedIn: UsersModule,the injectable is registered as a provider of theUsersModule without adding it to the providers of the module.

This new way has been introduced to have a better tree-shaking in theapplication. Currently a service added to the providers of a modulewill end up in the final bundle, even if it is not used in theapplication, which is a bit sad.

For more information please refer here


As always when multiple solutions are available it depends on what you want to achieve. But the documentation gives you some directive to choose.

Sometimes it's not desirable to have a service always be provided in the application root injector. Perhaps users should explicitly opt-in to using the service, or the service should be provided in a lazily-loaded context. In this case, the provider should be associated with a specific @NgModule class, and will be used by whichever injector includes that module.

So basically you will use providedIn: 'root' for any services that are application wide. For other services keep using the old version.

Don't forget that on you already had the choice to provide service differently. For instance it's also possible to declare Injectable at component level (this doesn't change in V6).

  @Component({    selector: 'app-my-component',    templateUrl: './my.component.html',    providers: [ MyService ]  })

This way the service becomes available only in MyComponent and its sub-component tree.


If You are using angular 5+ developer, it will automatically create the injectable service when declared as providedIn: 'root', in this case you will not required to import the service in app.module.ts. You can directly use it in another component.