mardi 29 mai 2018

How to create an Angular 6 service dinamically?

I'm looking for a transparent way to make HTTP requests using my ApiService classes. In the code below QuestionService, AuthService and RegisterService are children of ApiService.

The idea is to inject Api into a component in order to make a call like api.request('auth').get().

Basically, what I need is to remove the SERVICES map below and replace its reference by something like new window[name](this.http). Where name should be a string with the service name (ex: 'AuthService').

The problem is that services are not stored globally and I can't find how to access their classes. I looked at Injector class, but it requires a type, instead of a string ( https://angular.io/api/core/Injector ) .

const SERVICES = {
    'questions': QuestionService,
    'login': AuthService,
    'register': RegisterService,
};

@Injectable()
export class Api {
    public service: ApiService;

    constructor (private http: HttpClient) {

    }

    public request (name: string): Api {
        if (!SERVICES[name]) {
            throw new Error('Unknown service. ' + name + ' could not be found');
        }

        this.service = new SERVICES[name](this.http);
        return this;
    }
}

Any thoughts on how can I accomplish that?





Aucun commentaire:

Enregistrer un commentaire