【发布时间】:2019-10-04 04:55:05
【问题描述】:
当我的服务方法的subscribe 运行时,我得到的是一个对象而不是实际的类,我不知道为什么。我在我的服务中创建了一个方法,它返回一个基于 JSON 的实际类,而不是仅返回 json 接口:
getById(id: number): Observable<DetailsForLabAndCaller> {
return this.http.get<DetailsForLabAndCaller>(`${this.baseUrl}/${id}/new`).pipe(
tap(x => DetailsForLabAndCaller.fromJson(x))
);
}
我的fromJson 方法如下所示:
static fromJson(json: any): DetailsForLabAndCaller {
const ret: DetailsForLabAndCaller = Object.assign(new DetailsForLabAndCaller(), json);
ret.me = WorkerInfo.fromJson(ret.me);
ret.lab = Lab.fromJson(ret.lab);
console.info(`fromJson: has lab type: ${ret.lab instanceof Lab}`);
console.info(`fromJson: has WorkerInfo type: ${ret.lab.delegate instanceof WorkerInfo}`);
console.info(`fromJson: returns a DetailsForLabAndCaller: ${ret instanceof DetailsForLabAndCaller}`);
return ret;
}
调用服务时,我看到每条控制台消息都返回true。但是,当我尝试使用该服务时,我只是得到一个object,而不是一个实际的类对象:
this.spaceService.getById(id).subscribe(obj => {
console.info(`Call returned a real class: ${obj instanceof DetailsForLabAndCaller}`);
在前三个之后打印的控制台消息是false。为什么此时我只是得到一个香草对象而不是实际的类?
【问题讨论】:
-
在收到结果或一些鸭式检查后做 const ret: DetailsForLabAndCaller = Object.assign(new DetailsForLabAndCaller(), obj)
-
您可能想在
getById中使用map而不是tap。 -
@fridoo 成功了,谢谢。我不完全理解为什么点击在这里不起作用,因为订阅了该服务调用,所以看起来
tap也可以工作。如果您想将此作为答案发布,我会将其标记为正确。
标签: typescript rxjs angular7 rxjs6