2017-03-07 13 views
1

私は自分のデータサービスの基本クラスを持っています。私は、ポスト、get、例外ハンドラのような共通の機能を基本クラスに置きます。派生クラスは、Httpや基本クラスでのみ必要なものを使わずに基本クラスを継承する必要があり、基本クラスはそれ自身で依存関係を "解決"する必要があります。角2依存性注入

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

しかし、あなたは、私が見逃しているかもしれない1助言することができ、私は、「HTTPなしプロバイダ」のような例外が発生しましたか?

コンストラクタでサービスを注入すると、すべてうまく動作していました。サブクラスが明示的なコンストラクタを持っていない場合は、スーパークラスのコンストラクタが使用されている

enter image description here

答えて

2

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

も参照してください

+0

点は、サブクラスは(それが必要)依存性を注入するコンストラクタを持っている必要があることである、サブクラスは、ベースクラスで使用されるHTTPを気にしないはずです。これは正確に私が望むものではありませんが、別の投稿のあなたの答えは本当に助けになります。それはうまく動作します。 – khoailang

+0

サブクラスにコンストラクタがある場合、唯一のオプションは、サブクラスのコンストラクタ内のすべてのスーパーコンストラクタパラメータを繰り返し、 'super(...)'(または他の答え) –

関連する問題