为什么 Angular CLI 不自动在 providers 数组中添加服务?

Why doesn't Angular CLI add services in providers array automatically?

当我们使用angular-cli命令创建ComponentPipe时,CLI会自动将它们添加到特定模块的声明数组中,为什么在以下情况下不会发生这种情况服务。

直到 Angular 5,您应该将服务添加到 Angular 模块的 providers 数组以将其注册到 Angular 的注入器模块。

自 Angular 6 起,服务已成为 tree-shakable。

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.

因此,为了回答您的问题,如果您在 6.x.x 或更高版本上通过 Angular CLI 生成此服务,则很有可能该服务是在添加 providedIn: 'root' 的情况下生成的给 @Injectable 装饰器。因此它没有添加到 Angular 模块的 providers 数组中。