【问题标题】:Angular subscribe loses actual class typeAngular subscribe 丢失了实际的类类型
【发布时间】: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


【解决方案1】:

您在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))
    );
}

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2022-12-03
    • 2021-09-28
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多