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

Angular循环因未处理异常终止,需添加错误处理并维持循环运行

解决方案

核心修改思路

  1. 捕获并展示异常:用RxJS的catchError操作符抓HTTP请求的异常,新增变量存错误信息方便页面展示。
  2. 维持轮询不中断:在单个请求的流里处理错误,返回一个正常的Observable,避免错误扩散导致整个轮询停止。

修改后的完整代码

import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { of, Subject } from 'rxjs';
import { delay, tap, mergeMap, repeat, takeUntil, catchError } 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>();
  public curState: any;
  public errorMessage: string = ''; // 新增:存储错误提示信息

  constructor(private http: HttpClient) { }

  display = (response: any) => {
    if (response && Object.keys(response).length > 0) {
      console.log(response);
      this.curState = response;
      this.errorMessage = ''; // 请求成功时清空错误提示
    }
  };

  poll = of({}).pipe(
    mergeMap(_ => this.pollOmni().pipe(
      // 给单个请求加错误处理
      catchError((error) => {
        console.error('轮询请求失败:', error);
        this.errorMessage = `请求失败:${error.message || '未知错误'}`;
        // 返回空对象Observable,让轮询流继续走下去
        return of({});
      })
    )),
    tap(this.display),
    delay(200),
    repeat(),
    takeUntil(this.ngUnsubscribe)
  );

  pollOmni() {
    return this.http.post<any>('http://127.0.0.1:8084/api', { call: 'getInfo' });
  }

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

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

补充说明

你可以在组件模板里加{{ errorMessage }},这样用户能直接看到错误提示。如果不想在请求失败时执行display方法,把return of({})换成EMPTY(记得从'rxjs'导入EMPTY)就行,这样失败时会直接跳过tap步骤,继续下一轮轮询。等服务器恢复后,请求会自动恢复正常,错误提示也会被清空。

内容的提问来源于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 02:32:51