What's the best way to inject one service into another in angular 2 (Beta)?

前端 未结 7 1506
庸人自扰
庸人自扰 2020-11-22 05:25

I know how to inject a service into a component (via @Component), but how can I use DI to pass around services outside of components?

In other words, I don\'t want t

7条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:52

    First You need to provide your service

    You could provide it either in the bootstrap method:

    bootstrap(AppComponent,[MyFirstSvc]);
    

    or the on the app component, or in any other component, depending on your needs.:

    @Component({
        ...
          providers:[MyFirstSvc]
    }
    ...
    

    then just inject you service using the constructor :

    export class MySecondSvc {
          constructor(private myFirstSvc : MyFirstSvc ){}
    }
    

提交回复
热议问题