providedIn: The Angular 6 attribute you must start using

There’s a new attribute in Angular 6 and you need to start using it. Step forward the providedIn attribute… a new way to declare a tree-shakable provider.

Currently, when a service is registered it will end up in the final bundle even if it is not used. Webpack can’t perform its tree-shaking magic. Lazy loading won’t help either. The service can still get included in the lazy-loaded bundle even if the bundle doesn’t need it. providedIn solves this problem.

providedIn

providedIn Angular 6

The providedIn attribute makes it possible to register a service directly inside the @Injectable() decorator. It is no longer necessary to register a service in @NgModule().

providedIn: ‘root’ tells Angular to register the service as a singleton in the application root (equivalent to @NgModule({ providers: [ MessageService ]})

providedIn: UsersModule will register the service as a provider of the UsersModule. Again, no need to add the service to @NgModule.

@NgModule

Angular hasn’t removed the old way of registering services. There is no need to rewrite your old code. But going forward you must start using providedIn.

InjectionToken

providedIn works with any provider. For example, you can now declare an InjectionToken, directly register it with providedIn and give it a factory:

export const baseUrl = new InjectionToken<string>('baseUrl', {
  providedIn: 'root',
  factory: () => 'http://localhost:8080/'
});

One thought on “providedIn: The Angular 6 attribute you must start using

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.