简体   繁体   English

在再次调用API之前,如何在Angular中等待成功的API响应?

[英]How to wait for successful API responses in Angular before calling the API again?

Excuse me for a sloppy question, I really hope to find some help here. 请问一个草率的问题,我真的希望在这里找到帮助。

I am using Angular 6 for frontend and a .NET Core API for backend logic. 我将Angular 6用于前端,将.NET Core API用于后端逻辑。 The API makes calls to some external API's. 该API调用某些外部API。 There is a situation where I need to call an API periodically to check a status of an event. 在某些情况下,我需要定期调用API以检查事件的状态。 I make a call every 3 seconds, possible responses are "waiting", "ok", "cancel", "error" and so on. 我每3秒拨打一次电话,可能的响应是“正在等待”,“确定”,“取消”,“错误”等等。 In some situations the first call does not respond before the next call is executed, so I unnecessarily make two calls to an API. 在某些情况下,第一个调用在执行下一个调用之前没有响应,因此我不必要地对API进行了两次调用。

I've tried using .pipe(share().subscribe()), it solved the problem of delayed responses making unwanted actions on the client side, but other calls are still executed. 我尝试使用.pipe(share()。subscribe()),它解决了延迟响应的问题,使响应延迟在客户端产生了不必要的动作,但其他调用仍在执行。

Angular: 角度:

this.subscription = interval(3000).subscribe((value) => 
    this.someService.CheckCode(this.Code).pipe(share()).subscribe(
        result => { 

          /* Logic goes here... */

          this.subscription.unsubscribe();
        }
        ));

.NET Core API .NET Core API

        [HttpGet]
        public IActionResult CheckCode([FromQuery]string Code)
        {
            var result = GetStatus(Code); //This method performs a GetAsync method
                if (string.IsNullOrEmpty(result))
                    return BadRequest();
                return Ok(new { Token = result });
            }
            catch (Exception x)
            {
                return BadRequest();
            }
        }

I want to chain my calls so they wouldn't hit the API before a response is received. 我想链接我的调用,以便在收到响应之前它们不会打API。 The following request should only be made if I receive a response of "waiting" or if it the API takes too long to respond. 仅当我收到“正在等待”的响应或API花费的时间太长才能响应以下请求。

Any help would be highly appreciated. 任何帮助将不胜感激。

Try to add a flag to check if the previous API call is successful and then call it again. 尝试添加一个标志以检查先前的API调用是否成功,然后再次调用它。 This should be a straight forward approach. 这应该是一种直接的方法。

lastAPICall: boolean = true;

function makeAPICall() {
  if (this.lastAPICall) {
    this.lastAPICall = false;
    this.someService.CheckCode().subscribe(
      result => { 
         this.lastAPICall = true;
      }
    );
}

makeAPICall();

setInterval(makeAPICall, 3*1000);

I think, this should be handled by API with proper header response code. 我认为,这应该由具有适当标头响应代码的API处理。 If Execution of API is not completed then response code should be 202 and add retry after 3 seconds with call back URL. 如果API的执行未完成,则响应代码应为202,并在3秒后使用回调URL添加重试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM