Angular 6. Is it possible to inject service by con

2020-06-03 03:23发布

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条回答
smile是对你的礼貌
2楼-- · 2020-06-03 03:58

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

查看更多
登录 后发表回答