Angular service providedIn VS forRoot

Viewed 9476

I'd like to know if these two blocks of code are equivalent or not.

Can I use providedIn with the same result of forRoot?

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }
}

vs

@Injectable()
export class MyService {
  constructor() { }
}

@NgModule({
  imports: []
})
export class MyModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MyModule,
      providers: [
        MyService
      ]
    };
  }
}

@NgModule({
  imports: [
    MyModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

[I would still keep my MyModule for single use with the providedId singleton services]

3 Answers

Using providedIn vs providers[]:

  1. providedIn is the new Angular way of doing DI. providedIn was brought since Angular 6

  2. The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided

  3. Using providedIn: 'root' removes the need to import the library module at all, we can simply inject needed services and it just works

providedIn will directly injects the service based on the value - if its 'root' it will directly inject in root module - this will help you to stop adding your service in module [providers]

Angular will inject the service in the module - If in case you are using Lazy loading modules - angular will create new injectors whenever you load other modules

If you use Lazy loading is better to go with forRoot() injection on the modules and make sure your service doesn't create multiple injectors

Hope this helps you - Happy coding !!

Check this link for more info

Related