【问题标题】:Angular / RxJS: Sending an API request then polling another endpointAngular / RxJS:发送 API 请求然后轮询另一个端点
【发布时间】:2019-03-01 09:59:55
【问题描述】:

我想发送一个 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() 调用发出之前开始轮询?

【问题讨论】:

    标签: angular http rxjs observable


    【解决方案1】:

    尝试:

    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$));
    }
    

    【讨论】:

    • 就是这样,关键是使用startWith(null)强制第一次发射
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多