angular - 为什么 Angular CLI 不会自动在提供者数组中添加服务?

标签 angular dependency-injection angular-cli angular-di

就像我们创建 Component 时一样, Pipeangular-cli命令,CLI 会自动将它们添加到特定模块的声明数组中,为什么在服务的情况下不会发生这种情况。

最佳答案

在 Angular 5 之前,您应该向 providers 添加服务Angular 模块的数组,将其注册到 Angular 模块的注入(inject)器上。
从 Angular 6 开始,服务变成了可摇树的。

What is tree-shaking?

Well, in simple terms, it means that if you don't have an import statement for a particular service, then it won't be added as a part of your bundle. This will lead to a relatively smaller bundle size.

Why was Angular Services not tree-shakable before Angular 6?

Before Angular 6, you were expected to add a service to the providers array of an Angular Module so register them onto the injector of a service. And in order to do that, you'd have to add an import statement at the top of the file to actually refer to the service. And that would make it non-tree-shakable.

But this changed in Angular 6 after the introduction of the providedIn field in the @Injectable decorator's meta-data. If that's set to a value('root' for instance), then the service would be registered for dependency injection(to the root injector in this case).

And since it would be registered on the injector for dependency injection, we won't have to explicitly add it to the providers array of an Angular Module as that in-turn does the exact same thing. And not being required to add it to the declarations array means, not being required to add an import statement for it at the top of the file.

Which in turn would make the service tree-shakable if not in use.


因此,为了回答您的问题,如果您通过 Angular CLI 在版本 6.x.x 或更高版本上生成此服务,那么该服务很可能是使用 providedIn: 'root' 生成的。添加到 @Injectable装饰师。所以它没有被添加到 providers Angular 模块的数组。

关于angular - 为什么 Angular CLI 不会自动在提供者数组中添加服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131633/

相关文章:

angularjs 2 cli,构建 chrome 扩展,定义内容和后台脚本的麻烦

angular - 如何在 Angular/ ionic 的每个服务调用中显示/隐藏加载程序?

angular - 我们可以有两个具有相同选择属性的 ng-content 吗?

php - 业务逻辑放在 Lumen 哪里?

java - Guice DI 绑定(bind),无需添加 Guice 注解

angular - 使用开关时 tslint 提示 "statements must be filtered with an if statement"

angular - 如何在不干扰/覆盖 Angular Material 设计的情况下以 Angular 使用引导网格样式

angular - 在 Angular 6 中重置响应式表单时不会禁用输入

asp.net-core - 如何在类似 StructureMap 的 Scrutor 中注册程序集上的所有接口(interface)

Angular - 工作区中未设置配置