【问题标题】:Angular 7/ RxJs : Poll endpoint with response of first endpointAngular 7/ RxJs:轮询端点,响应第一个端点
【发布时间】:2019-05-10 14:36:18
【问题描述】:

我有一个端点(initiate$),我点击它,它返回一个queueId,用那个queueId我点击另一个端点,直到那个端点返回就绪状态。我有一些有效的代码,但它连续调用两个端点。我知道为什么它会同时调用两者,但我不知道如何最好地将调用分开,以便在后续调用中仅点击第二个端点 (status$)。

RxJs:“^6.3.3”

downloadTransactionList() {
  const initiate$ = this.exampleService.startListExport(userId, filter);
  const status$ = this.exampleService.pollListExport(initiate$);
  const polling$ = timer(0, 10000).pipe(
    mergeMap(() => status$),
    takeWhile(resp => resp.status !== 'ready')
  );
  initiate$.pipe(mergeMap(() => polling$)).subscribe(r => console.log(r));
}

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    使用shareReplay() 运算符。它通过 ReplaySubject 多播源 observable(换句话说 - ReplaySubject 订阅源并将它的最后一个值广播给未来的观察者)。

    this.exampleService.startListExport(userId, filter).pipe(shareReplay())

    供参考,这里是a DEMO

    【讨论】:

      【解决方案2】:

      使用 switchMap 代替 mergeMap

      【讨论】:

      • 我切换到switchMap,它仍在调用两个端点
      【解决方案3】:

      如果我对您的理解正确,您希望最初调用一次获取队列 id,然后启动轮询器来轮询数据,直到返回的状态准备就绪正确?

      试试下面的

      downloadTransactionList() {
         // This calls startListExport to get the queue id
         this.exampleService.startListExport(userId, filter).subscribe((queueId:string) => {
             // When it has successfully returned, initiate the poller
             let timerSubscription:Subscription = timer(0, 10000).pipe(switchMap(() => {
                 // Assuming this returns an observable with the status
                 return this.exampleService.pollListExport(queueId);
             })).subscribe((data:myType) => {
                 // DO something with your data
      
                 // Unsubscribe to stop the poller when criteria is met
                 if (data.status === 'ready') {
                    timerSubscription.unsubscribe();
                 }
             })
         });
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多