Typescript 实际的类类型
当我的服务方法的Typescript 实际的类类型,typescript,rxjs,angular7,rxjs6,Typescript,Rxjs,Angular7,Rxjs6,当我的服务方法的subscribe运行时,我得到的是一个对象而不是实际的类,我不知道为什么。我在我的服务中创建了一个方法,该方法返回一个基于JSON的实际类,而不仅仅是JSON接口: getById(id:number):可观察{ 返回this.http.get(`${this.baseUrl}/${id}/new`).pipe( 点击(x=>DetailsForLabAndCaller.fromJson(x)) ); } 我的fromJson方法如下所示: static fromJson(j
subscribe
运行时,我得到的是一个对象而不是实际的类,我不知道为什么。我在我的服务中创建了一个方法,该方法返回一个基于JSON的实际类,而不仅仅是JSON接口:
getById(id:number):可观察{
返回this.http.get(`${this.baseUrl}/${id}/new`).pipe(
点击(x=>DetailsForLabAndCaller.fromJson(x))
);
}
我的fromJson
方法如下所示:
static fromJson(json:any):DetailsForLabAndCaller{
const-ret:DetailsForLabAndCaller=Object.assign(新的DetailsForLabAndCaller(),json);
ret.me=WorkerInfo.fromJson(ret.me);
ret.lab=lab.fromJson(ret.lab);
info(`fromJson:has lab type:${ret.lab instanceof lab}`);
info(`fromJson:has WorkerInfo type:${ret.lab.delegate instanceof WorkerInfo}`);
info(`fromJson:返回DetailsForLabAndCaller:${ret instanceof DetailsForLabAndCaller}`);
返回ret;
}
调用服务时,我看到每个控制台消息都返回true
。然而,当我尝试使用该服务时,我只是得到一个对象
,而不是实际的类对象:
this.spaceService.getById(id).subscribe(obj=>{
info(`Call返回了一个实类:${obj instanceof DetailsForLabAndCaller}`);
在前三个之后打印的控制台消息是:
false
。为什么我现在只得到一个普通对象而不是实际的类?您在getById
中使用了点击,它只是传递传入值,通常用于副作用。因此返回的值ode>DetailsForLabAndCaller.fromJson(x)
从未使用。要实际映射到返回值,必须使用map
getById(id: number): Observable<DetailsForLabAndCaller> {
return this.http.get<DetailsForLabAndCaller>(`${this.baseUrl}/${id}/new`).pipe(
map(x => DetailsForLabAndCaller.fromJson(x))
);
}
getById(id:number):可观察{
返回this.http.get(`${this.baseUrl}/${id}/new`).pipe(
映射(x=>DetailsForLabAndCaller.fromJson(x))
);
}
您在getById
中使用了点击,它只传递传入值,通常用于副作用。因此,从不使用来自DetailsForLaband.fromJson(x)
的返回值。要实际映射到返回值,您必须使用map
getById(id: number): Observable<DetailsForLabAndCaller> {
return this.http.get<DetailsForLabAndCaller>(`${this.baseUrl}/${id}/new`).pipe(
map(x => DetailsForLabAndCaller.fromJson(x))
);
}
getById(id:number):可观察{
返回this.http.get(`${this.baseUrl}/${id}/new`).pipe(
映射(x=>DetailsForLabAndCaller.fromJson(x))
);
}
Just do const ret:DetailsForLabAndCaller=Object.assign(新的DetailsForLabAndCaller(),obj)在收到结果或一些鸭子类型检查后,您可能想使用map
而不是getById
@fridoo中的tap
,谢谢。我不完全理解为什么tap在这里不起作用,因为该服务调用已订阅,所以似乎tap
也能起作用。如果您要将此作为答案发布,我会将其标记为正确。只需执行const-ret:DetailsForLabAndCaller=Object.assign(新DetailsForLabAndCaller(),obj)在收到结果或一些鸭子类型检查后,您可能想使用map
而不是getById
@fridoo中的tap
,谢谢。我不完全理解为什么tap在这里不起作用,因为该服务调用已订阅,所以似乎tap
也能起作用。如果您如果你想把这个作为一个答案,我会把它标记为正确的。