我在挣扎于angular2的依赖注入。在我的例子中,我有两个服务。
我必须在组件中提供Service2
@Component({
providers: [Service1, Service2]
}),但为什么?我给Service2注射了Service1。为什么我必须在组件中提供Service2,而在组件中没有对Service2的引用?
我知道,我可以在我的引导函数中提供服务,但是我想向我的组件提供我的服务。
bootstrap(AppComponent, [... Service1, Service2])下面是我的示例代码,由于缺少提供程序,它无法工作。
component.ts
import {Service1} from "service1.ts";
@Component({
providers: [Service1]
})
export class Component{
constructor(private s: Service1) {
//get data from Service1
}
}service1.ts
import {Service2} from "service2.ts";
@Injectable()
export class service1{
constructor(private s2: Service2) {
//get data from service2
//edit data
//return data
}
}service2.ts
@Injectable()
export class service2{
constructor() {
//return data
}
}发布于 2016-07-13 20:44:01
角需要知道,哪里可以找到服务。这就是提供者数组(无论是在组件中还是在引导调用中)的用途。您可以将其视为分层注册表。如果您希望注入服务,则需要将它们提供给注册表。
在Angular1中,服务是通过调用factory函数或类似方式在注册表中注册的。这里的逻辑是不同的。
总之,即使组件没有直接绑定到服务,它也必须注册它,这样角才能意识到它的存在。
https://stackoverflow.com/questions/38360690
复制相似问题