Angular: providedIn makes singleton services tree-shakeable
Starting from Angular 6, if you want to provide a singleton service it’s recommended to use providedIn
:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
…instead of the providers
array we’ve always used in the past:
@NgModule({
...
providers: [UserService],
...
})
(examples are copied from the documentation)
OK, so what’s the big deal? I just realized this is not just a fancy syntax, but it makes your services tree-shakeable, as noted in the docs. Since they’re no longer referenced directly by AppModule
, the services can be moved to the lazily-loaded bundles which need them. As a result, switching to providedIn
would most probably shrink your main bundle considerably, making the initial load slightly faster!