简体   繁体   English

Angular 2-7中的PROVIDER,INJECTOR和SERVICE有什么区别?

[英]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.

相关问题 @Inject(Injector)注入器和注入器有什么区别? - what is the difference between @Inject(Injector) injector and injector? 反射式注入器与角度注入器之间的区别 - Difference between Reflective Injector and Injector in Angular 这些在 Angular 8 中创建服务的方法有什么区别? - What is the difference between these create service method in Angular 8? Angular Testing中没有$ injector的提供者 - No provider for $injector in Angular Testing 角,提供者或注入者,它们创建一个服务实例 - Angular, provider or injector, which one creates a service instance 注入@Component中的提供程序和@Module之间的Angular2有什么区别? - What is the difference in Angular2 between inject a provider in @Component and @Module? 如何在angularjs和angular(2-7)应用程序之间共享数据或事件 - How to share data or event between angularjs and angular (2-7) applications 在Angular 2中使用Injector时没有提供程序 - No provider while using Injector in Angular 2 Typescript / Angular 4:注入服务和初始化为新类有什么区别? - Typescript / Angular 4: What is the difference between injecting a service and initializing as new class? Angular:在组件中声明服务和引导过程之间的区别是什么 - Angular: what is the difference between declaring a service in a component and the bootstrap process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM