我有以下service
:
import {Injectable} from 'angular2/core';
import {Service2} from './app.service2';
@Injectable()
export class Service1 {
constructor(service2:Service2) {
this.service2 = service2;
}
getData() {
return this.service2.getData();
}
}
我在我的某个组件中使用此服务,但我不确定这个service
如何接受service2
作为参数?传统上,在JS我做这样的事情。
var s = new Service1(service2);
但是我在下面没有看到这样的东西,但它确实有效。 https://plnkr.co/edit/PsySVcX6OKtD3A9TuAEw?p=preview
任何人都可以对此有所了解。
答案 0 :(得分:3)
Angular2使用dependency injection(DI)创建实例。它为您创建组件,指令,管道和服务的类实例。为此,它检查构造函数参数及其注册的matchin实例提供者列表,当DI为您调用new Xxx(...)
时,它会传递在其提供者列表中找到的所有提供者,而一个未找到它将引发异常。
如果其中一个类具有带参数的构造函数,则该类需要一个装饰器(@Component()
,@Directive()
,@Pipe()
或@Injectable()
之一。表示DI需要分析构造函数。