[英]What is the difference between PROVIDER, INJECTOR and SERVICE in Angular 2-7?
Could anyone please explain to me the differences in simpler words. 有谁能请用简单的词语向我解释这些差异。 Any real-time example with or without code would also work.
任何有或没有代码的实时示例也可以。
A service is a class in Angular which is registered with an Angular dependency injector. 服务是Angular中的一个类,它使用Angular依赖注入器注册。 In the below example, StudentService class is a service.
在下面的示例中,StudentService类是一项服务。
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class StudentService {
constructor() { }
}
An Angular injector is responsible for creating service instances and injecting them into classes. Angular进程器负责创建服务实例并将它们注入类中。 Usually injectors work behind the scenes.
通常注射器在幕后工作。 Below code shows injector being explicitly created.
下面的代码显示了显式创建的注入器
constructor(private injector: Injector) { }
The below code inject the service directly to the host component. 以下代码将服务直接注入主机组件。
injector.get(Service)
Providers tell the injector how to create the service. 提供商告诉注入器如何创建服务。 Without a provider, the injector would not know that it is responsible for injecting the service nor be able to create the service.
如果没有提供者,注入器将不知道它负责注入服务,也不能创建服务。 Usually, providers are mentioned in the module or component metadata.
通常,在模块或组件元数据中提及提供程序。 For example, if a component want to call the service 'FileWriter', the component should mention in the metadata, that this service should be created and injected by the injector.
例如,如果组件想要调用服务“FileWriter”,则组件应在元数据中提及应该由注入器创建和注入此服务。
providers: [FileWriter]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.