在哪里注册Angular 2服务,以便它可以全局使用



我有一个服务,比如ServiceA,它执行许多服务器通信工作。此服务在整个应用程序中被包括ServiceB在内的其他服务大量使用。有没有一种方法可以让我注册一次(即在应用程序组件中),以便所有在子组件中注册的服务都可以使用它?现在看来,我必须将其与调用它的每个服务一起注册。

当我将ServiceA添加到AppComponent的viewProviders数组时,当注入器试图将ServiceB注入子组件时,我会得到一个No provider for ServiceA!异常。

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 {}

服务A

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

服务B

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

子组件

 @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) {}
}

注入服务的最佳方式与当前相同,只是使用providers选项而不是通过AppComponent中的viewProviders注入服务。您只需要在根组件中包含providers选项,但必须记住在每个文件中导入服务并将其注入构造函数。

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

相关内容

最新更新