Angular 提供商做什么以及如何使用它?

What Angular Providers do and how to use it?

我是 Angular 的新手。我按照此 link, and i tried to do/add something that doesn't part of that tutorial. I added a providers :[EmployeeService] line to employee-list.component.ts and empployee.component.ts inside @component, and it returns error that said TypeError: Cannot read property 'push' of undefined. So realize that adding providers :[EmployeeService] to some components are unnecessary. I read about Dependency Injection from this link 中的教程进行操作,但我并没有真正了解我想知道的内容。那么谁能给我一个简单的解释 how/when/where 到 use/put 提供者以及该错误是如何发生的?

非常感谢您。

providers 数组告诉 Angular 它应该实例化哪些服务。你可以在两个地方定义它:

  1. 组件
  2. 模块

当您在组件中使用提供程序时,该服务及其所有子项都可用。

当您在模块中使用它时,服务将可用于给定模块中的所有管道、指令、组件和服务。

但是您可以根据需要在两者中定义它 - 在这种情况下 Angular 将创建同一服务的两个实例。

开始在模块级别提供您的服务。