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

前端 未结 7 1368
庸人自扰
庸人自扰 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:58
    • "Provide" your services somewhere at or above where you intend to use them, e.g., you could put them at the root of your application using bootstrap() if you only one once instance of each service (singletons).
    • Use the @Injectable() decorator on any service that depends on another.
    • Inject the other services into the constructor of the dependent service.

    boot.ts

    import {bootstrap} from 'angular2/platform/browser';
    import {AppComponent} from './app.component';
    import {MyFirstSvc} from '../services/MyFirstSvc';
    import {MySecondSvc} from '../services/MySecondSvc';
    
    bootstrap(AppComponent, [MyFirstSvc, MySecondSvc]);
    

    MySecondSvc.ts

    import {Injectable} from 'angular2/core';
    import {MyFirstSvc} from '../services/MyFirstSvc';
    
    @Injectable()
    export class MySecondSvc {
      constructor(private _firstSvc:MyFirstSvc) {}
      getValue() {
        return this._firstSvc.value;
      }
    }
    

    See Plunker for other files.

    What's a bit odd about Service DI is that it still depends on components. E.g., MySecondSvc is created when a component requests it, and depending on where MyFirstSvc was "provided" in the component tree, that can affect which MyFirstSvc instance is injected into MySecondSvc. This is discussed more here: Can you only inject services into services through bootstrap?

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