0

The scenario is:

ServiceA is accessed by two components having inputs. ComponentA has textArea and ComponentB has toggle button. On change of these components, ServiceA.save() is called. save() does HTTP call.

Now the problem is:

I enter text in textarea of componentA and directly click on toggle of componentB (Without clicking out of the textArea). Hence 2 events - blur and click - occurred at the same time and ServiceA.save() is called. This is the leading calling of another API while the previous call isn't complete. How do I put a check or stop it until the other call completes?

export class ServiceA {
  constructor() {}
  save() {
    this.ServiceB.callApi(reqLink, key, data).subscribe(
      (resData) => {
        console.log("API successful!");
      },
      (rej) => {
        console.log("Error occured!");
      }
    );
  }
}

The answers would be appreciated!

3
  • So do you want to cancel the second request, or pause it until the first one completes? Commented Jul 23, 2020 at 10:29
  • One possibility is to disable the textarea and button during the request, but that's not really user friendly. Another is to manually queue all changes, but you need to implement the queue logic yourself. You could also put saving on a timeout, so changing both in quick succession will only trigger a single save. Commented Jul 23, 2020 at 10:47
  • well, disable controls that should'nt be used during loading and showing some "in progress" indicator is definitely the user experience I would hope for. Commented Jul 23, 2020 at 11:08

1 Answer 1

4

You need a flag, which signals if the execution is already running. I assume, you want to completely skip the execution if it's already running:

// Use a class variable as a flag
private saveIsRunning = false;
save(){    
  // Skip the execution, if it's already running.
  if (this.saveIsRunning) {
    return;
  }
  this.saveIsRunning = true;

  this.ServiceB.callApi(reqLink, key, data).subscribe((resData) => {
    console.log('API successful!');
    this.saveIsRunning = false;
  },
  (rej) => {
    console.log('Error occured!');
    this.saveIsRunning = false;
  });
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

I actually want to execute the api and not skip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.