4

I have a basic ServiceBase class which injects Http into the constructor:

import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

export abstract class ServiceBase<T> {
    constructor(private http: Http) {
    }

    protected getData(url: string): Promise<T> {
        return this.http.get(url).toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

This is then extended by the child class:

@Injectable()
export class WeatherService extends ServiceBase<Weather> {
    constructor(http: Http) {
        super(http);
    }

    getWeather(): Promise<Weather> {
        return this.getData('api/weather');
    }
}

However, I want to avoid having to inject Http into all of my child classes and passing the parameter into the parent class by calling super(http); is this at all possible? I only need to inject Http in the base class since the child classes will all be calling methods from the parent class which uses the service.

DGibbs
  • 14,316
  • 7
  • 44
  • 83

1 Answers1

0

Yes it is possible with the ReflectiveInjector.

import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

export abstract class ServiceBase<T> {

    protected http: Http;
    
    constructor() {
      const injector = ReflectiveInjector.resolveAndCreate([
      Http,
      BrowserXhr,
      {provide: RequestOptions, useClass: BaseRequestOptions},
      {provide: ResponseOptions, useClass: BaseResponseOptions},
      {provide: ConnectionBackend, useClass: XHRBackend},
      {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
    ]);
     this.http = injector.get(Http);
    }

    protected getData(url: string): Promise<T> {
        return this.http.get(url).toPromise()
            .then(response => response.json() as T)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.log('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}
Yoni Affuta
  • 284
  • 1
  • 5