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
也能起作用。如果您如果你想把这个作为一个答案,我会把它标记为正确的。