18

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.

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
Alex Bryanskiy
  • 395
  • 1
  • 3
  • 19

2 Answers2

27

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

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
2

Another variant use @Inject decorator, if condition compute outside current class.

export interface IService {
  test: string;
}


@Injectable()
export class Serivce1 implements IService {
  test: 'service1';
}

@Injectable()
export class Serivce2 implements IService {
  test: 'service2';
}

const CONDITION = Math.random() > 0.5;
    
@Component({
   selector: 'my-app',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css'],
})
export class AppComponent {
   name = 'Angular ' + VERSION.major;
    
   constructor(@Inject(CONDITION ? Serivce1 : Serivce2) private service: IService) {
        console.warn(service);
   }
}