Reputation: 29
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. The API makes calls to some external API's. There is a situation where I need to call an API periodically to check a status of an event. I make a call every 3 seconds, possible responses are "waiting", "ok", "cancel", "error" and so on. In some situations the first call does not respond before the next call is executed, so I unnecessarily make two calls to an 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.
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
[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. The following request should only be made if I receive a response of "waiting" or if it the API takes too long to respond.
Any help would be highly appreciated.
Upvotes: 0
Views: 2209
Reputation: 41
I think, this should be handled by API with proper header response code. If Execution of API is not completed then response code should be 202 and add retry after 3 seconds with call back URL.
Upvotes: 1
Reputation:
Try to add a flag to check if the previous API call is successful and then call it again. 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);
Upvotes: 0