Angular / TypeScript将服务注入基类,但不在子类中

时间:2017-11-08 12:42:39

标签: angular typescript inheritance dependency-injection

我有一个基本ServiceBase类,它将Http注入构造函数:

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

然后由子类扩展:

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

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

但是,我想避免必须将Http注入我的所有子类中,并通过调用super(http);将参数传递给父类,这是否可能?我只需要在基类中注入Http,因为子类都将从使用该服务的父类调用方法。

1 个答案:

答案 0 :(得分:0)

是的,可以使用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);
    }
}