为什么我不应该在 Angular 2 中的组件中提供服务

Why shouldn't I provide services in components in Angular 2

如果我想在整个应用程序中使用服务,我应该在 app.module.ts 中将其声明为提供者,但如果在 app.component.ts 中声明它也可以。

这两种方法有什么显着差异吗?

假设您在 AppModule 中声明了三个组件。如果您在每个组件中单独提供服务,每个组件都会有自己的服务实例,但如果您在 AppModule 中提供它,您的服务将是单例的 - 每个组件将共享 一个相同的实例 该服务。

使用 app.module.tsapp.component.ts 只是一个 naming convention and doesn't programmitcally determine anything in Angular. The code will work wherever your service lives. It may make more sense to instead put your services into a service-name.service.ts 文件,不在 app.module.ts 中。但是,正如 Stefan Svrkota 的回答中所指出的那样,无论在哪个地方,您都可以获得代码重用的优势