javascript - Angular 无法在类中初始化服务 (HttpClient)

标签 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 from within the base class function.

我的“AppUser”实例显然是从“BaseResource”继承find,但是find 正在选取“AppUser”实例作为this< 的值http 不可用。我曾尝试将 http 声明为公共(public)和私有(private)以及 protected ,但这没有效果。我想我错过了一些关于如何扩展类(class)的大局。

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

(使用 Angular 6.0.4)

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

最佳答案

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

你应该将HttpClient注入(inject)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!
  }
}

关于javascript - Angular 无法在类中初始化服务 (HttpClient),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51367472/

相关文章:

javascript - 如何在 jQuery 数组中找到 indexOf 元素?

angular - 找不到模块 '@angular/elements' : Angular 7

javascript - 一起使用 TypeScript 和 Vuejs 时的对象级变量?

angular - 如何使用 Angular 2(typescript) 将数据和图像都传递到 "ASP.NET Core"Web API?

javascript - 如何使用 javascript 在图像中移动?

c# - 在 C# ASP.NET AJAX 中使用 $get

Angular 2 : API call return an error

Angular : open sidenav with another component , 错误类型错误:无法读取未定义的属性 'toggle'

express - 当我使用 typescript 时,我如何使用 express 的 cookie-parser

javascript - jQuery 动画 : Change the destination of a prop during the animation