2017-08-17 116 views
1

我想實現一個服務,所有其他服務將擴展來處理API響應。我跟着這個問題角2:父類依賴注入是undefined

Inheritance and dependency injection

,這裏是我的父類:

import {Injector} from '@angular/core'; 
import {Router} from "@angular/router"; 
import {Response} from "@angular/http"; 

export class ApiService { 

    protected _router: Router; 

    constructor(injector: Injector) { 
    console.log('inside ApiService constructor'); 
    this._router = injector.get(Router); 
    console.log(this._router); 
    } 

    extractData(res: Response) { 
    if (res.json().status === 200) { 
     return res.json().data; 
    } 
    } 

    extractResponse(res: Response) { 
    if (res.json().status === 200) { 
     return res.json(); 
    } 
    } 

    handleErrorPromise(error: Response | any) { 
    console.log('inside handleErrorPromise'); 
    console.error(error.message || error); 
    console.log(this._router); 

    if (error.status === 401 || error.status === "401") { 
     // session out 
     this._router.navigate(['/login']); 
    } else { 
     return Promise.reject(error.json().message | error.message || error); 
    } 
    } 

} 

和這裏的擴展它的服務:

@Injectable() 
export class VitalService extends ApiService { 

    constructor(private http: Http, injector: Injector) { 
    super(injector); 
    } 

    getUserVitals(): Promise<VitalDashboardItem[]> { 
    return this.http.get('/gch-restful/vital-entry/dashboard') 
     .toPromise() 
     .then(response => { 
     return response.json().data as VitalDashboardItem[]; 
     }) 
     .catch(this.handleErrorPromise); 
    } 

} 

,但是當它到達handleErrorPromise超class

我得到這個錯誤:

Error: Uncaught (in promise): TypeError: Cannot read property '_router' of undefined 
TypeError: Cannot read property '_router' of undefined 

我一直試圖找出現在有什麼不對,嘗試了幾件事情,沒有運氣。任何幫助表示讚賞

編輯

改成了這樣:

getUserVitals(): Promise<VitalDashboardItem[]> { 
    return this.http.get('/gch-restful/vital-entry/dashboard') 
     .toPromise() 
     .then(response => { 
     return response.json().data as VitalDashboardItem[]; 
     }) 
     .catch((e) => { 
     return this.handleErrorPromise(e) 
     }); 
    } 
+1

'console.log(this._router);'你在這裏得到什麼? –

+0

它不是沒有定義在那裏。打印路由器對象 – HeisenBerg

回答

3

你在這裏失去了this背景:

.catch(this.handleErrorPromise); 

將其更改爲:

.catch((e) => { this.handleErrorPromise(e) }); 

查看How to properly do a 「bind」 in angular2 typescript?的信息。

+0

對不起,但它仍然顯示無法讀取屬性'_router'未定義 – HeisenBerg

+0

它在哪裏顯示它?什麼線? –

+0

console.log(this._router);裏面的handleErrorPromise方法 – HeisenBerg