Home > front end >  What is proper way to have a "finally" / "complete" code block for a subscriptio
What is proper way to have a "finally" / "complete" code block for a subscriptio

Time:10-22

I have a modal, with a button that is disabled when clicked, and then makes an api call.. Regardless of success or failure, I want to enable the button upon api call completion. If it's successful, then dismiss the modal. If it fails, show an error message.

this.buttonDisabled = true;
this.client.post(this.formGroup.value).pipe(
  first()
).subscribe(
  () => this.dismissModal(),
  (error) => this.setError(error),
  () => { this.buttonDisabled = false; }
)

I am seeing the success and failure functions get called, but not the "finalize/complete" one... Is there another way to have shared code between success/failure without duplicating it?

Also, just want to verify I am doing the pipe/first/subscribe thing right.. This approach, I do not need to unsubscribe right? because I did first() ?

CodePudding user response:

You can use the finalize pipe operator

this.client.post(this.formGroup.value).pipe(
  first(),
   finalize(() => this.buttonDisabled = false;),
).subscribe(
  () => this.dismissModal(),
  (error) => this.setError(error),
 )
  • Related