Angular 6. Is it possible to inject service by condition?

前端 未结 1 535
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 18:57

In my angular app (with the angular material) I have a filter panel and I want besides select to be able to make autocomplete (user input value and it sends to the back-end, whe

相关标签:
1条回答
  • 2021-02-07 19:08

    Yes you can inject service dynamically using injector.get()

    Sample code :

    import { Component, Injector } from '@angular/core';
    import { MyService } from './my.service';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      myService : MyService;
    
      constructor(private injector : Injector){
        if(true){ // some condition
          this.myService = injector.get<MyService>(MyService);
        }
    
        console.log(this.myService.prop1)
      }
    }
    

    Working demo

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