angular 6 dependency injection

匆匆过客 提交于 2019-12-29 10:53:47

问题


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

@Injectable({
  providedIn: 'root',
})
export class HeroService {}

However the documentation still also refers to registering the service in the module providers array in the module metadata just like we did in Angular 5:

@NgModule({
  providers: [HeroService],
})
export class AppModule {}

So,

  • Which method should be used to make the injector aware of the service that it should inject?
  • Will the module providers array method be deprecated?

回答1:


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



回答2:


If You are using angular 5+ developer, it will automatically create the injectable service when declared as providedIn: 'root', in this case you will not required to import the service in app.module.ts. You can directly use it in another component.




回答3:


The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors.

The @Injectable() decorator has the providedIn metadata option, where you can specify the provider of the decorated service class with the root injector, or with the injector for a specific NgModule.

In your case, because it has been providedIn at "root" level, no need to add this again as a provider in the module.

More about Dependency Injection Here



来源:https://stackoverflow.com/questions/50208642/angular-6-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!