用于服务相关服务的Angular 2提供程序,未由bootstrap()实例化

时间:2016-06-29 19:31:27

标签: angular

服务B保存对服务A的引用 - 如果我通过Angular2 bootstrap()方法实例化服务A,我需要做的就是在服务B中添加对服务A的引用构造函数和Angular愉快地将服务A注入服务B ...但是如果组件1需要它自己的服务B实例,组件2需要它自己的服务B实例...服务B怎么样?提供其依赖服务A的唯一实例(例如,组件1和服务A的状态不应受组件2的服务A状态的影响)? ---这意味着服务B需要能够实例化独立服务A实例......我想我可以在服务A中new服务B(但这不是依赖注入)......对于注入服务的服务,我基本上需要providers: []元数据......

或(更简单地说)

有人可以共享从bootstrap()方法或组件以外的某个地方提供的服务的代码示例吗?

3 个答案:

答案 0 :(得分:2)

不幸的是,服务无法提供依赖关系。

您可以做的最好的事情是导出提供者数组并在所需的组件中提供它。

Export class ServiceB {
  constructor(serviceA: ServiceA) {}
 ... 
}

Export const SERVICEB_PROVIDERS = [ ServiceB, ServiceA ];

然后在组件中:

@Component {
  ... 
  providers: [SERVICEB_PROVIDERS]
  ... 
}

有关详细信息,请参阅角度回购中的github issue

答案 1 :(得分:1)

在@Component中指定提供程序属性时,您告诉依赖项注入为此特定组件提供新实例。

如果您未在提供程序中指定服务,则依赖关系请求会冒泡下一个父组件,并将继续在每个父组件中查找提供程序,直到找到提供程序或获取引导程序函数。

这将为Component1提供它自己的ServiceB。它不会引用您在引导程序中提供的那个:

@Component({
    selector: "Component1",
    templateUrl: "./blah/component1.component.html",
    providers: [ServiceB]
})
export class Component1{
...

如果在父组件中找不到另一个提供者属性,那么这个将从您的引导函数中获取ServiceB。

@Component({
    selector: "Component2",
    templateUrl: "./blah/component2.component.html"
})
export class Component2{
...

答案 2 :(得分:0)

我偶然发现了Victor Savkin's blog post about Angular Dependency Injection

的摘录
// Angular 2: Configuring LoginService

@Injectable() class LoginService {
  constructor(@Inject("LoginServiceConfig") public config: {url: string}) {}
  //...
}

@Component({
  selector: 'app',
  template: `<login></login>`,
  directives: [Login],
  providers: [
        LoginService,
        provide("LoginServiceConfig", {useValue: {url: 'myurl'})
    ]
})
class App {}

它说明了如何将(子)服务注入到(父)服务中,其中注入(父)服务的(子)服务(必须是?)由组件使用其中的父组件提供(其中) parent)服务提供给组件......

相关问题