首页 > 解决方案 > Angular / RxJS:发送 API 请求然后轮询另一个端点

问题描述

我想发送一个 API 请求,然后轮询另一个端点,直到success: true从第二个端点返回带有正文的响应。我正在使用 Angular 的 HTTPClient 来提出我的请求。我最初的想法是这样做:

createConversion(request): Observable<any> {
    return this.http.post('/endpoint', request).pipe(

      // This is the problem: I want to start polling before this post() call emits

      mergeMap((response) => {

        // Start polling

        return timer(0, 5000).pipe(
          takeUntil(this.converted$),
          concatMap(() => {

            return this.http.get('/second-endpoint')
          })
        )
      })
    );

post()但是,直到第一个调用与第一个请求的响应一起发出,才会调用 mergeMap 。是否有一个 RxJS 操作员可以让我在第一次post()调用发出之前开始轮询?

标签: angularhttprxjsobservable

解决方案


尝试:

createConversion(request): Observable<any> {
    const post$ = this.http.post('/endpoint', request).pipe(startWith(null)); 
    // force fake emission
    const get$ = this.http.get('/second-endpoint');
    const polling$ = timer(0,5000).pipe(mergeMap(_=> get$), takeUntil(this.converted$));

    return post$.pipe(mergeMap(_=> polling$));
}

推荐阅读