简体   繁体   中英

Angular service providedIn VS forRoot

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]

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

Yes, forRoot and provideIn both are equivalent since both will create the only and only one singleton for the app. Even though it being loaded in lazy loaded component.

Refer this nice article on it - https://medium.com/@chrishouse/when-to-use-angulars-forroot-method-400094a0ebb7

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM