Angular 订阅丢失实际 class 类型
Angular subscribe loses actual class type
当我的服务方法 subscribe
运行时,我得到一个对象而不是实际的 class,我不明白为什么。我在我的服务中创建了一个方法,该方法 return 是一个基于 JSON 的实际 class,而不是仅 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;
}
调用服务时,我会看到每条控制台消息 return true
。但是,当我随后尝试使用该服务时,我只是得到了一个 object
,而不是一个实际的 class 对象:
this.spaceService.getById(id).subscribe(obj => {
console.info(`Call returned a real class: ${obj instanceof DetailsForLabAndCaller}`);
在前三个之后打印的控制台消息说 false
。为什么我现在只得到一个原始对象而不是实际的 class?
您在 getById
中使用了 tap
,它只是传递传入值,通常用于副作用。所以从未使用 DetailsForLabAndCaller.fromJson(x)
的返回值。要实际映射到返回值,您必须使用 map
.
getById(id: number): Observable<DetailsForLabAndCaller> {
return this.http.get<DetailsForLabAndCaller>(`${this.baseUrl}/${id}/new`).pipe(
map(x => DetailsForLabAndCaller.fromJson(x))
);
}
当我的服务方法 subscribe
运行时,我得到一个对象而不是实际的 class,我不明白为什么。我在我的服务中创建了一个方法,该方法 return 是一个基于 JSON 的实际 class,而不是仅 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;
}
调用服务时,我会看到每条控制台消息 return true
。但是,当我随后尝试使用该服务时,我只是得到了一个 object
,而不是一个实际的 class 对象:
this.spaceService.getById(id).subscribe(obj => {
console.info(`Call returned a real class: ${obj instanceof DetailsForLabAndCaller}`);
在前三个之后打印的控制台消息说 false
。为什么我现在只得到一个原始对象而不是实际的 class?
您在 getById
中使用了 tap
,它只是传递传入值,通常用于副作用。所以从未使用 DetailsForLabAndCaller.fromJson(x)
的返回值。要实际映射到返回值,您必须使用 map
.
getById(id: number): Observable<DetailsForLabAndCaller> {
return this.http.get<DetailsForLabAndCaller>(`${this.baseUrl}/${id}/new`).pipe(
map(x => DetailsForLabAndCaller.fromJson(x))
);
}