2017-08-17 180 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