2

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";
    }
}

1 Answer 1

4

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');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.