Ex:
I have 2 services
1) one.service.ts
2) two.service.ts
And I have a component - dashboard.component.ts
import { Component, ViewEncapsulation, Inject } from '@angular/core';
import { OneService } from '../services/one.service';
import { TwoService } from '../services/two.service';
@Component({
selector: 'dashboard',
encapsulation: ViewEncapsulation.Emulated,
styleUrls: ['./dashboard.less'],
templateUrl: './dashboard.html'
})
export class DashboardComponent {
constructor() {
// Here how do I get service instance based on some this condition.
if(true) {
/* Service **one.service.ts** to be injected */
} else {
/* Service **two.service.ts** to be injected */
}
}
}
You can use the
Injector
As @MeirionHughes mentioned this is called the service locator pattern:
Source: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#explicit-injector
And again as mentioned you can get these injectors in another service and then inject this service into your component.