Angular 2 Dependencies Injection

时间:2017-03-07 07:55:05

标签: angular dependency-injection

我将为我的数据服务提供基类。我在基类中放置了像post,get,exception handler这样的常用函数。派生类只需要继承没有Http的基类或只在基类中使用的必要东西,基类需要自己“解析”它的依赖关系。

import { Injectable, ReflectiveInjector } from '@angular/core'
import { Http, RequestOptions, Headers, Request, Response } from '@angular/http';
import { Observable } from 'rxjs';

export class DataServiceBase{
    private _injector: ReflectiveInjector;
    private get injector() : ReflectiveInjector{
        if(this._injector == null)
            this._injector = ReflectiveInjector.resolveAndCreate([Http]);

        return this._injector;
    }

    private _http: Http;
    private get http(): Http{
        if(this._http == null)
            this._http = this.injector.get(Http);

        return this._http;
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleException(exception: any) {
        console.error(exception);
        return Observable.throw(exception.statusText);
    }

    protected post(url: string, data: any): Observable<any> {
        var headers = new Headers({ 'Content-Type': 'application/json' });
        var options = new RequestOptions({ headers: headers });

        var body = JSON.stringify(data);

        return this.http.post(url, body, options)
            .map(this.extractData)
            .catch(this.handleException);
    }

    protected get(url: string) : Observable<any> {
        return this.http.get(url)
            .map(this.extractData)
            .catch(this.handleException);
    }
}
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs';

import { TodoItem } from '../model/todoItem';

import { DataServiceBase } from './dataServiceBase';

@Injectable()
export class ValidationSampleService extends DataServiceBase{
    constructor(){
        super();
    }

    public getAllTodoItem(): Observable<any>{
        return this.get('/api/todo');
    }

    public updateToDoItem(item: any){
        return this.post('/api/todo/updateTodoItem', item);
    }
}

但我得到了一个例外,例如“没有Http提供者”,你能告诉我哪一个我可能会错过吗?

如果我在构造函数中注入服务,那么一切正常。

enter image description here

1 个答案:

答案 0 :(得分:2)

如果子类没有显式构造函数,则使用超类的构造函数:

export class DataServiceBase{
  constructor(private http:Http){}
export class ValidationSampleService extends DataServiceBase{
    // constructor(){
    //    super();
    // }

另见