【问题标题】:Angular 2: parent class dependency injected is undefinedAngular 2:注入的父类依赖项未定义
【发布时间】:2018-01-25 10:31:09
【问题描述】:

我正在尝试实现一个服务,所有其他服务都将扩展它以处理 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)
      });
  }

【问题讨论】:

  • console.log(this._router); 你来这里做什么?
  • 那里不是未定义的。打印路由器对象

标签: angular dependency-injection routing angular2-services


【解决方案1】:

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

.catch(this.handleErrorPromise);

改成:

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

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

【讨论】:

  • 抱歉,还是显示Cannot read property '_router' of undefined
  • console.log(this._router);在handleErrorPromise 方法内
  • 你是怎么修改代码的?显示更新版本
  • 我把 console.log(this);就在 console.log(this._router); 之前它打印未定义
  • 你更新.catch((e) =&gt; { this.handleErrorPromise(e) });了吗?如果是这样,请在此处输入日志.catch((e) =&gt; { console.log(this._router); this.handleErrorPromise(e) });
猜你喜欢
  • 2016-04-15
  • 2016-02-15
  • 1970-01-01
  • 2016-06-20
  • 2017-03-28
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多