我想通过从类中创建数据访问对象来隔离 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/