Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 664
Alex Bryanskiy Avatar asked Aug 31 '18 07:08

Alex Bryanskiy


People also ask

What are the different ways to inject the Angular service?

Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency. Interface injection: The dependency provides an injector method that will inject the dependency into any client passed to it.

What is injectable () in Angular service?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

Can we use service without injectable?

If you want to use angular services (and Http is an angular service) you must inject them as I told above as a constructor attribute to another service / component , which means if you want to use Http you need to have your service injectable. So the answer is no, you can't do it in a nice way.

How do you inject a service into an angular component?

Components consume services; that is, you can inject a service into a component, giving the component access to that service class. To define a class as a service in Angular, use the @Injectable () decorator to provide the metadata that allows Angular to inject it into a component as a dependency .

How does heroservice injection work in angular?

When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments. The process of HeroService injection looks something like this. You must register at least one provider of any service you are going to use.

What happens if we don’t have an injector in angular?

The first injector with the provider configured gives the dependency to our constructor. If we do not have any provider all the way up to the root injector, the Angular DI framework would then throw an error.

What is the use of angular in AngularJS?

Angular does help you follow these principles by making it easy to factor your application logic into services and make those services available to components through dependency injection. Here's an example of a service class that logs to the browser console.


2 Answers

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

like image 125
Amit Chigadani Avatar answered Oct 12 '22 05:10

Amit Chigadani


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);
   }
}
like image 31
Андрей Керничный Avatar answered Oct 12 '22 05:10

Андрей Керничный