简体   繁体   English

在哪里注册Angular 2服务,以便可以在全球范围内使用它?

[英]Where to register an Angular 2 Service such that it can be used globally?

I have a Service, say ServiceA, that performs a lot of server communication work. 我有一个服务,例如ServiceA,可以执行很多服务器通信工作。 This service is used heavily by other services, including ServiceB, throughout the application. 在整个应用程序中,此服务被其他服务(包括ServiceB)大量使用。 Is there a way that I can register it once (ie. in the App Component) such that it is available to all services that are being registered in child Components? 有没有一种方法可以将其注册一次(即在App Component中),以使其可用于子组件中正在注册的所有服务? Right now it seems that I have to register it alongside each Service that calls it. 现在看来,我必须在调用它的每个Service旁边注册它。

When I add ServiceA to the viewProviders array of the AppComponent, I'm getting a No provider for ServiceA! 当我将ServiceA添加到AppComponent的viewProviders数组中时,我获得了No provider for ServiceA!No provider for ServiceA! exception when the injector tries to inject ServiceB into a child component. 注入程序尝试将ServiceB注入子组件时发生异常。

AppComponent AppComponent

 @Component({
  moduleId: module.id,
  selector: 'app1',
  viewProviders: [..., **ServiceA**],<--I WANT TO DO THIS SO ITS AVAILABLE EVERYWHERE
  templateUrl: 'app.component.html',
  directives: [...]
})
export class AppComponent {}

ServiceA 服务A

@Injectable()
export class ServiceA {
    constructor(http: Http) {}
}

ServiceB 服务B

@Injectable()
export class ServiceB {
    constructor(serviceA: ServiceA) {}
}

ChildComponent ChildComponent

 @Component({
  moduleId: module.id,
  selector: 'app1',
  viewProviders: [ServiceB,**ServiceA**], <-AND I DON'T WANT TO HAVE TO DO THIS EVERY TIME
  templateUrl: 'app.component.html',
  directives: [...]
})
export class ChildComponent {
    constructor(private serviceB, ServiceB) {}
}

The best way to inject a service is the same as you are currently doing, except that instead of injecting it via the viewProviders in the AppComponent, use the providers option. 注入服务的最佳方法与您当前所做的相同,只是使用providers选项代替通过AppComponent中的viewProviders注入服务。 You will only have to include the providers option in the root component, but you will have to remember to import the service on each file and inject it in the constructor. 您只需要在根组件中包括providers选项,但是您必须记住要在每个文件上导入服务并将其注入构造函数中。

@Component({
    moduleId: module.id,
    selector: 'app1',
    providers: [ServiceA],
    templateUrl: 'app.component.html',
    directives: [...]
})
export class AppComponent {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM