在Angular 2中进行注入.它是如何工作的? [英] Injection in Angular 2. How does it work?

查看:52
本文介绍了在Angular 2中进行注入.它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习Angular 2几天了.当我了解Angular 2中的Injectable()概念并尝试在此链接中应用教程的示例代码时:

I've been learning Angular 2 for a few days now. When I read about the Injectable() concept in Angular 2 and try to apply the tutorial's example code in this link : Angular 2 - Dependency Injection, I get a problem.

他们说我需要在类的顶部放置注解@Injectable(),以便其他类可以进行注入,例如:

They said I need to put the annotation @Injectable() on top of the class so that the other classes can inject, like:

import { 
   Injectable 
} from '@angular/core'; 

@Injectable() 
export class appService {  
   getApp(): string { 
      return "Hello world"; 
   } 
}

问题是当我放下Injectable()时,我的应用仍然可以正常运行.有人可以帮我弄清楚Angular 2中的注入是如何工作的吗?

The problem is that when I drop Injectable(), my app still runs properly. Can someone help me figure out how does injection in Angular 2 work?

推荐答案

文档中已明确指出:

碰巧,您可能已经从第一个版本的 HeroService 中省略了 @Injectable(),因为它没有注入的参数.但是,由于服务具有注入的依赖关系,因此您现在必须拥有它.您需要它,因为Angular需要构造函数参数元数据才能注入 Logger .

As it happens, you could have omitted @Injectable() from the first version of HeroService because it had no injected parameters. But you must have it now that the service has an injected dependency. You need it because Angular requires constructor parameter metadata in order to inject a Logger.

https://angular.io/guide/dependency-injection#why-injectable

因此,简而言之,如果您的注射剂具有注射剂,则 @Injectable 装饰器将解析循环依赖性.


"Angular 2中的注入如何工作?"

So in short, if your injectables have injectors, the @Injectable decorator resolves the cyclic-dependency.


" how does injection in Angular 2 work?"

这是一个非常广泛的问题,但总而言之,Angular注入系统会创建该提供程序对象/函数的实例,并在构造函数中注入时在该组件中使用该实例.

This is a really broad question but to sum up Angular injection system creates an instance of that provider object/function and uses that instance in that component when you inject it in the constructor.

如果尚未在正在使用的组件中提供 ,则它将转到它的父组件,直到找到实例的已使用模块为止.每个级别都有自己的提供程序实例映射,并且该组件将使用向上遍历注入树时找到的第一个实例.

If you haven't provided it in the component that you are using then it will go to it's parent component, up to the module that it's been used until it finds the instance. Each level has its own map of provider instances and the component will use the first instance that it finds when it traverses the injection tree upwards.

因此,提供者将一直是一个单实例,直到定义为止.

So the provider will be a singleton instance up to the point it is defined.

这篇关于在Angular 2中进行注入.它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆