【发布时间】:2018-12-24 08:01:55
【问题描述】:
我想通过从类中创建数据访问对象来隔离 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”实例,因为this 和http 的值不可用。我尝试将http 声明为公共和私有以及受保护,但这没有任何效果。我想我错过了一些关于如何扩展类的大图。
尽可能具体地,我认为我的问题是当函数需要访问基类的上下文时,如何将它们抽象为基类。
(使用 Angular 6.0.4)
编辑 我更新了标题,因为很明显这是在类中实例化 HttpClient 服务的问题。
【问题讨论】:
-
是抛出编译错误还是runtme错误?从我所见,你永远不会在任何地方初始化
http,所以它是未定义的。 -
该错误是运行时错误。我在 BaseResource 中导入
HttpClient。它不是通过构造函数注入的,因为(我认为)这会阻止“更新”实例。不过,在这一点上我当然可能是错的。 -
是的,导入它不会创建实例,它只是类型安全所需要的。您是否需要直接注入
BaseResource,或者它总是一个扩展BaseResource的类? -
如果我还需要实例化它,也许stackoverflow.com/questions/49507928/… 有我的答案。我的意图是永远不要直接使用 BaseResource。
标签: javascript angular typescript