0

I'm using ng-zorro components in my project, and I want to show a model that calls a service to delete an entry, this is how I defined the delete confirm dialog :

  showDeleteConfirm(id: string): void{
    this.modal.confirm({
      nzTitle: 'Êtes-vous sûr de vouloir supprimer ce enregistrement ?',
      nzOnOk: () => {
          this.service.delete(id).subscribe(data => {
          this.notification.create("success", "Suppression", "L'enregistrement a été supprimée !");
        });
      }
    });
  }

But I had this issue where the code inside the subscribe function is executed multiple times.

How can I solve this ?

Edit:

This is my delete function :

delete(id: string): any{
  return this.http.delete<Entity>(this._apiURL + id, this.httpOptions).pipe(
    catchError(this.handleError)
  );
}
private handleError(err: HttpErrorResponse) {
  let errorMessage = '';
  if (err.error instanceof ErrorEvent) {
    errorMessage = `An error occurred: ${err.error.message}`;
  } else {
    errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
  }
  return errorMessage;
}
4
  • 2
    Can you please provide the code of your delete function. Commented Jan 18, 2019 at 16:51
  • @Batajus please check my edit Commented Jan 21, 2019 at 15:41
  • Is it possible that your subscription is called twice every time? Commented Jan 21, 2019 at 16:52
  • @Batajus when I debug that code showDeleteConfirm function is only called once, but the code inside subscribe function is called multiple times. Commented Jan 22, 2019 at 8:36

1 Answer 1

1

In case you would like to make sure that code inside subscribe is executed once, you can use take(1) or first()

Example:

this.service.take(1).subscribe(...);

Also, the best practice is always to use takeUntil() and destroy it for example in ngOnDestroy

class myComponent {
  private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

  constructor(
    private service: Service) {}

  ngOnInit() {
    this.service
      .takeUntil(this.destroyed$)
      .subscribe(...);
  }

  ngOnDestroy() {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.