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

后端 未结 3 547
傲寒
傲寒 2020-12-14 01:33

I want to inject a service to another service:

@Injectable()

export class Dispatcher {
}


@Injectable()

export class TodoStore {

    constructor(@Inject(         


        
相关标签:
3条回答
  • 2020-12-14 01:39

    You need to provide your service somewhere. Please refer to angular2 docs

    You could provide it in the bootstrap method:

    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. It's basically the same as

    constructor(dispacher:Dispatcher){
    }
    

    Oh yeah, welcome to SO :)

    0 讨论(0)
  • 2020-12-14 01:47

    A providers array is available in @NgModule. You can provide your service by declaring your service in that array.

    @NgModule({
        declarations:[...],
        imports:[...],
        providers: [MyCustomService],
        bootstrap:[AppComponent]
    })
    
    0 讨论(0)
  • 2020-12-14 01:48

    Thank for the reply.

    Since it is not a Component, the @Component(...) solution does not apply.

    bootstrap(AppComponent,[TodoStore,Dispatcher]); 
    

    solution works. But that makes this main.ts a central place.

    0 讨论(0)
提交回复
热议问题