javascriptangulartypescripterror-handlinginterceptor

How can I show only one alert for multiple deletions in angular?


I have a code like this =>

return next.handle(req).pipe(
  map((response: any) => {
    if ( req.method !== "GET" && response instanceof HttpResponse && response.status === 200) {
      this.alertService.showSuccessAlert();
    }
  return response;
}),

I want to show only one alert in multiple deletion. In the current scenario, one alert is shown per deleted item on the page, so this means a mess when 10 items are deleted.

I tried to solve by creating a boolean variable but it didn't work.

EDIT: my component =>

multipleDeleteCategory() { 
  const selectedCategories = this.myForm.value.selectedCategory;
   if (selectedCategories && selectedCategories.length > 0) { 
    selectedCategories.forEach((category: Category) => { 
      this.categoryService.deleteCategory(category.id).subscribe(() => { 
        this.categories = this.categories.filter(cat => cat.id !== category.id); 
      }); 
    }); 
  } 
}

Alert Service =>

public showSuccessAlert(): void { 
  this.toastrService.success('Your transaction has been completed', 'Success:', this.getAlert()); }

Solution

  • I think you need to use this method findDuplicate to check if the message already exists, if it does not, then show the popup!

    you code

    public showSuccessAlert(): void { 
        if(!this.toastrService.findDuplicate('Your transaction has been completed', 'Success:', false, true)) {
            this.toastrService.success('Your transaction has been completed', 'Success:', this.getAlert()); 
        }
    }
    

    Below example, clicking success multiple times, will not work, if there is already a popup open!

    Stackblitz Demo


    findDuplicate source code

    /**
       * Determines if toast message is already shown
       */
      findDuplicate(title = '', message = '', resetOnDuplicate: boolean, countDuplicates: boolean) {
        const { includeTitleDuplicates } = this.toastrConfig;
    
        for (const toast of this.toasts) {
          const hasDuplicateTitle = includeTitleDuplicates && toast.title === title;
          if ((!includeTitleDuplicates || hasDuplicateTitle) && toast.message === message) {
            toast.toastRef.onDuplicate(resetOnDuplicate, countDuplicates);
            return toast;
          }
        }
    
        return null;
      }