Angular无法初始化类中的服务(HttpClient)

时间:2018-07-16 17:47:42

标签: javascript angular typescript

我想通过从类创建数据访问对象来隔离http交互,以便在组件中我可以像这样简单地获取数据:

// dashboard.component
import { AppUser } from './appuser.service'

export class DashboardComponent implements OnInit {
  user: AppUser = new AppUser();

  constructor() { }

  ngOnInit() {
    let id = JSON.parse(window.localStorage.getItem('session')).userId;
    this.user.find(id) // 'find' is from base class
      .subscribe(
        // handle user data
      );
  }
}

我已经定义了一个基类和一个子类:

// base-resource.service
import { HttpClient } from '@angular/common/http';
...
export class BaseResource {
  private fullpath: string;
  protected http: HttpClient;

  constructor (path: string) {
    this.fullpath = path;
  }

  find (id): Observable<Object> {
    return this.http.get(this.fullpath + '/' + id); // this line throws Error!
  }
}

// app-user.service
...
export class AppUser extends BaseResource {
  constructor(data?) {
    super('api/appusers');
  }
}

但这会产生错误:ERROR TypeError: Cannot read property 'get' of undefined来自基类函数。

我的'AppUser'实例显然是继承自'BaseResource'的find,但是find却选择了'AppUser'实例作为thishttp的值不可用。我曾尝试将http声明为公共和私有以及受保护的,但这没有任何效果。我想我缺少关于如何扩展类的大图。

尽可能具体地讲,我认为我的问题是当函数需要访问基类的上下文时如何将其抽象为基类。

(使用Angular 6.0.4)

编辑 我更新了标题,因为很明显这是在类中实例化HttpClient服务的问题。

1 个答案:

答案 0 :(得分:1)

错误是因为没有实例化HttpClient,所以在使用它时未定义。

您应该将HttpClient注入AppUser,并通过构造函数将其传递到BaseResource

export class AppUser extends BaseResource {
  constructor(HttpClient http) {
    super(http, 'api/appusers');
  }
}

在base-resource.service中

import { HttpClient } from '@angular/common/http';
...
export class BaseResource {
  private fullpath: string;
  protected http: HttpClient;

  constructor (httpClient: HttpClient, path: string) {
    this.fullpath = path;
    this.http = httpClient;
  }

  find (id): Observable<Object> {
    return this.http.get(this.fullpath + '/' + id); // this line throws Error!
  }
}