简体   繁体   English

Angular 2:将服务注入另一个服务。 (没有提供者错误)

[英]Angular 2: Inject Service to another service. (No provider error)

I want to inject a service to another service:我想将一个服务注入另一个服务:

@Injectable()

export class Dispatcher {
}


@Injectable()

export class TodoStore {

    constructor(@Inject(Dispatcher) dispatcher:Dispatcher){ 

    }
}

But I always get Error: No provider for Dispatcher!但我总是收到错误:没有 Dispatcher 的提供者!

Thanks.谢谢。

You need to provide your service somewhere.您需要在某处provide服务。 Please refer to angular2 docs请参阅angular2 文档

You could provide it in the bootstrap method:您可以在 bootstrap 方法中提供它:

bootstrap(AppComponent,[TodoStore,Dispatcher]);

or the app component:或应用程序组件:

@Component({
    ...
      providers:[TodoStore,Dispatcher]
}
...

Or in any other component, depending on your needs.或在任何其他组件中,具体取决于您的需要。

Also, you don't need to @Inject(Dispatcher) in the constructor.此外,您不需要在构造函数中@Inject(Dispatcher) It's basically the same as它基本上与

constructor(dispacher:Dispatcher){
}

Oh yeah, welcome to SO :)哦,是的,欢迎来到 SO :)

Thank for the reply.感谢您的回复。

Since it is not a Component, the @Component(...) solution does not apply.由于它不是一个组件,@Component(...) 解决方案不适用。

bootstrap(AppComponent,[TodoStore,Dispatcher]); 

solution works.解决方案有效。 But that makes this main.ts a central place.但这使得main.ts成为一个中心位置。

A providers array is available in @NgModule. @NgModule 中提供了一个提供者数组。 You can provide your service by declaring your service in that array.您可以通过在该数组中声明您的服务来提供您的服务。

@NgModule({
    declarations:[...],
    imports:[...],
    providers: [MyCustomService],
    bootstrap:[AppComponent]
})

Try this: 尝试这个:

myMainService.ts myMainService.ts

import { myOtherService } from 'myOtherService';

export class myMainService {
 constructor() {
   let myOtherService = new myOtherService();
 }
}

myOtherService.ts myOtherService.ts

export class myOtherService {
    constructor() {
        console.log('service was imported');
    }
}

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

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