Angular轮询时Catch未触发,是否需调整位置以捕获错误?
问题修复:连接中断时轮询停止且catchError未触发
你的问题出在两个核心点:
- catchError位置错误:当前catchError放在mergeMap外层,一旦单次请求出错,捕获后抛出异常会直接终止整个轮询流,导致repeat无法继续执行。正确做法是把catchError放到mergeMap内部,针对每一次单独的请求做错误处理,单个请求失败不会打断整个轮询循环。
- 错误处理后抛出异常:catchError里用
throw会让流直接终止,应该返回一个合法的Observable(比如of(null)),让轮询流能继续运转。
修复后的完整代码:
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>(); // 用于取消订阅的Subject public curState; constructor(private http: HttpClient) { } display = response => { if (response) { // 处理错误时返回的null情况 console.log(response); this.curState=response; } }; poll = of({}).pipe( mergeMap(_ => this.pollOmni().pipe( // 将catchError移至此处,针对单个请求处理错误 catchError(err => { console.log("捕获到错误:", err); // 返回of(null)让流继续,而非抛出异常终止流 return of(null); }) )), tap(this.display), delay(200), repeat(), takeUntil(this.ngUnsubscribe), // 当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(); // 完成Subject } }
关键修改说明:
- 把
catchError移入mergeMap内部,包裹this.pollOmni(),确保每次请求的错误被单独捕获,不影响整体轮询流。 - 错误处理时返回
of(null)替代抛出异常,保证流不终止,repeat能继续发起下一轮请求。 - 在
display方法中增加响应判断,避免错误场景下的null值覆盖现有状态。
内容的提问来源于stack exchange,提问作者mark
相关产品推荐
相关产品推荐

