You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何解析HTTP响应并获取服务器返回的JSON数据?

解决方法:获取HTTP请求返回的JSON数据

问题根源

你代码里的callOmni方法用of(this.pollOmni())把HTTP请求返回的Observable又包装了一层,导致mergeMap处理后传递给display的还是Observable对象,不是服务器返回的实际JSON。

快速修复

方案1:修改callOmni方法

去掉多余的of()包裹,直接返回pollOmni的结果:

callOmni = () => this.pollOmni();

方案2:简化代码(推荐)

直接在mergeMap里调用HTTP请求,去掉callOmni中间层,让逻辑更清晰:

poll = of({}).pipe(
  mergeMap(_ => this.http.post<any>('http://127.0.0.1:8044/api', { call: 'getInfo' })),
  tap(this.display),
  delay(10),
  repeat(),
  takeUntil(this.ngUnsubscribe)
);

改完之后,display函数里的response就是服务器返回的JSON数据,打印就能看到正确结果。

完整修复代码

import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of, Subject } from 'rxjs';
import { delay, tap, mergeMap, repeat, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  private ngUnsubscribe = new Subject<void>();

  constructor(private http: HttpClient) { }

  display = (response: any) => {
      console.log(response); // 现在输出服务器返回的JSON
  };

  poll = of({}).pipe(
    mergeMap(_ => this.http.post<any>('http://127.0.0.1:8044/api', { call: 'getInfo' })),
    tap(this.display),
    delay(10),
    repeat(),
    takeUntil(this.ngUnsubscribe)
  );

  ngOnInit() {
    this.poll.subscribe();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

补充说明

  • HttpClient.post()本身就返回Observable类型,不需要额外用of()包装,否则会产生Observable嵌套的情况。
  • mergeMap的作用是展平嵌套的Observable,但如果一开始就没嵌套,它会直接订阅内层Observable并返回其发射的数据,这正是我们需要的。

内容的提问来源于stack exchange,提问作者mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 01:47:19