【问题标题】:set delay for 5 sec after one API call在一次 API 调用后设置延迟 5 秒
【发布时间】:2019-02-26 12:34:24
【问题描述】:

在我的项目中,我面临一个挑战。即..我需要一个一个调用多个API调用。在这里,我使用 RxJS flatMap 运算符。它按预期工作。但我的额外要求是我需要为每个 API 调用设置 10 秒的延迟。我使用了“节流”运算符,但它不起作用。我在下面附上了我的代码。谁能告诉我们我的代码做错了什么。

public makeSubmitAPI(oncallData): Observable<any> {
        let orderPayload = this.postAPIService.prepareOrderPayload(oncallData);
        let url = "";
        let orderResponse: any;
        return this.apiCallsService.apiCall('placeOrder', orderPayload, 'post', false)
            .map((orderRes: any) => {
                orderResponse = orderRes;
                url = `orders/${orderResponse.data.id}/progress`;
                let progressPayload = this.postAPIService.prepareProgressAPIData(oncallData, orderResponse.data, this.userType);
                return progressPayload;
            }).pipe(throttle(val=> interval(5000)))
            .flatMap(progressPayload => {
                    return this.apiCallsService.apiCall(url, progressPayload, 'post', false).pipe(throttle(val=> interval(5000)))
            })
            .flatMap(progressResponse => {
                return Observable.combineLatest(
                    orderResponse.data.serviceAddresses.map((address, index) => {
                        let fullfilledAPI = this.postAPIService.prepareFullfilledAPIData(oncallData, orderResponse.data, progressResponse, this.userType, index, orderPayload);
                        return this.apiCallsService.apiCall('fullfillment', fullfilledAPI, 'post', false).map(res => res);
                    })
                )
            });
    }

谢谢

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    您可以使用concatMap(而不是包装 API 调用的flatMap)进行一个接一个的调用,然后使用delay() 来强制实现您想要的 5 秒延迟:

    .concatMap(progressPayload => this.apiCallsService.apiCall(url, progressPayload, 'post', false)
      .pipe(
        delay(5000)
      )
    })
    

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 2019-02-28
      • 2019-04-21
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多