我想實現一個服務,所有其他服務將擴展來處理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)
});
}
'console.log(this._router);'你在這裏得到什麼? –
它不是沒有定義在那裏。打印路由器對象 – HeisenBerg