How to conditionally inject service into component?

后端 未结 1 1212
遥遥无期
遥遥无期 2020-12-09 18:50

I have 2 services one.service.ts and two.service.ts, and a component dashboard.component.ts.

How to conditionally inject those

1条回答
  •  囚心锁ツ
    2020-12-09 19:07

    You can use the Injector

    import { Injector } from '@angular/core'  
    ...
    constructor(private injector: Injector){ 
    
      if(true) {
        this.oneService = this.injector.get(OneService);
      } else {
        this.twoService = this.injector.get(TwoService);
      }
    }
    

    As @MeirionHughes mentioned this is called the service locator pattern:

    The technique is an example of the service locator pattern.

    Avoid this technique unless you genuinely need it. It encourages a careless grab-bag approach such as you see here. It's difficult to explain, understand, and test. You can't know by inspecting the constructor what this class requires or what it will do. It could acquire services from any ancestor component, not just its own. You're forced to spelunk the implementation to discover what it does.

    Framework developers may take this approach when they must acquire services generically and dynamically.

    Source: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector

    And again as mentioned you can get these injectors in another service and then inject this service into your component.

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