angular 6 dependency injection

后端 未结 1 1803
盖世英雄少女心
盖世英雄少女心 2020-12-12 17:41

In the latest release of Angular 6, a service is registered in a module using the providedIn property in the service metadata:

@Injectable({
  p         


        
相关标签:
1条回答
  • 2020-12-12 18:43

    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, directly inside the @Injectable() decorator, using the new providedIn attribute. It accepts 'root' as a value or any module of your application. When you use 'root', your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule, the injectable is registered as a provider of the UsersModule without adding it to the providers of the module.

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

    For more information please refer here

    • https://blog.ninja-squad.com/2018/05/04/what-is-new-angular-6/
    • https://angular.io/guide/dependency-injection#injectable-ngmodule-or-component
    • https://angular.io/guide/hierarchical-dependency-injection#moduleinjector [As suggested by Tuan-Tu in comment below]
    0 讨论(0)
提交回复
热议问题