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

独自空忆成欢 提交于 2019-12-09 09:23:43

问题


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, whereby $regexp query we find the match in MongoDB collection). But to do it I need manually inject service into filters component. I didn't find any info on how to do it.

I need something like this:

if (filters.serviceName) {
  injector.inject(serviceName);
}

injector.get(serviceName).find(searchQuery);

Is it possible? Thanks.


回答1:


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



来源:https://stackoverflow.com/questions/52110168/angular-6-is-it-possible-to-inject-service-by-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!