如何以响应式编程方式结合interval实现数据定时刷新?
问题根因
你在exhaustMap的内部Observable中使用了switchMap(() => this.items$),而items$是BehaviorSubject类型,属于永远不会主动完成的热Observable。exhaustMap的运行规则是:只要内部Observable还未结束,就会忽略所有上游interval发射的新值。第一次请求完成后,内部流切换到了一直存活的items$,永远不会结束,因此后续interval每5秒触发的信号全部被exhaustMap忽略,自然不会再发起新的HTTP请求。
修复方案
方案1:简化流逻辑(更推荐)
你的核心需求是定时拉取数据、避免重复请求、结果存入items$、模板可订阅拿到最新值,不需要在请求流中切换到items$,直接调整流结构即可:
@Component({ selector: "app-root", template: ` {{ items$ | async | json }} ` // 直接订阅存储结果的items$即可 }) export class AppComponent { title = "CodeSandbox"; // 存储服务端返回结果 items$ = new BehaviorSubject(null); // 定时请求触发流 private reloadTrigger$ = interval(5 * 1000).pipe( startWith(0), exhaustMap(() => this.http.get(this.url)), tap(res => { console.log({ res }); this.items$.next(res); }) ); url = "https://randomfox.ca/floof/"; constructor(private http: HttpClient) { // 订阅触发流启动定时请求 this.reloadTrigger$.subscribe(); } }
方案2:保留单管道订阅写法
如果你希望仅在模板中使用一个async管道,不需要额外手动订阅,可以给items$加上take(1),保证内部Observable每次请求完成后正常结束,不阻塞后续interval触发:
@Component({ selector: "app-root", template: ` {{ reload | async | json }} ` }) export class AppComponent { title = "CodeSandbox"; items$ = new BehaviorSubject(null); reload = interval(5 * 1000).pipe( startWith(0), exhaustMap(() => this.http.get(this.url).pipe( tap(r => { console.log({ r }); this.items$.next(r); }), // 仅取一次items$的最新值,让内部流正常结束,不阻塞下一次请求触发 switchMap(() => this.items$.pipe(take(1))) ) ) ); url = "https://randomfox.ca/floof/"; constructor(private http: HttpClient) {} }
内容的提问来源于stack exchange,提问作者Jon Sud
相关产品推荐
相关产品推荐

