Angular 2:未定义注入的父类依赖项

时间:2017-08-17 06:15:50

标签: angular dependency-injection routing angular2-services

我正在尝试实现一项服务,所有其他服务都会扩展该服务来处理api响应。我关注了这个问题

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时

我收到了这个错误:

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 个答案:

答案 0 :(得分:3)

您在这里失去了this上下文:

.catch(this.handleErrorPromise);

将其更改为:

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

有关信息,请参阅How to properly do a “bind” in angular2 typescript?