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

前端 未结 7 1370
庸人自扰
庸人自扰 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条回答
  •  被撕碎了的回忆
    2020-11-22 05:39

    The first thing to do is to annotate all services with the @Injectable annotation. Notice the parentheses at the end of the annotation, without this this solution won't work.

    Once this is done, we can then inject services into each other using constructor injection:

    @Injectable()
    export class MyFirstSvc {
    
    }
    
    @Injectable()
    export class MySecondSvc {
        constructor(helpfulService: MyFirstSvc) {        
        }
    }
    
    @Injectable()
    export class MyThirdSvc {
        constructor(helpfulService: MyFirstSvc) {        
        }
    }
    

提交回复
热议问题