piernik
piernik

Reputation: 3657

Getting service based on classname using injector

In angular 2 I want to have one parent Service that can be extended to specific Services. Component's attribute would say which Service to use. Problem is that I don't know how to do that because injector.get() needs class as param - not classname. Here is code sample.

import {Injectable, Injector, Provider} from '@angular/core';

@Injectable()
export class ObjectFactoryService {

    constructor(private injector: Injector) {
    }

    getObjectService(tableId: string): Provider {
        //return this.injector.get(SpecificService); - works but this is class not classname
        return this.injector.get(this.createObjectServiceName(tableId)); //error - provider not exists
    }

    private createObjectServiceName(tableId: string): string {
        return tableId.charAt(0).toUpperCase() + tableId.slice(1) + "Service";
    }
}

Upvotes: 2

Views: 918

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658067

If you provide classes with a string token, you can acquire them using a string token

providers: [MyClass, {provide: 'MyClass', useExisting: MyClass}]
myClass = this.injector.get('MyClass');

Upvotes: 4

Related Questions