-1

I update multiple records using the following update method and receive the updated and failed record count from result. Then I want to display related toastr message sequentially using Angular Material toastr. However, the following approach skip the success in #1 (or it is displayed back of the error) and display the error in #2. So, how can I display them sequentially for this method? Maybe I need to use RxJs for this purpose.

update() {
    this.demoService.update(...).toPromise()
    .then(result => {
      if(result.success.count > 0){
        // #1 display success toastr
      }
      if(result.failed.count > 0) { 
        // #2 display error toastr
      }
    }).catch(err => {
        // #3 display error toastr related to other errors
    });
}

1 Answers1

0

definitelly you need to use Rxjs Observables instead of Promises if you work with Angular :d

So, your code will become:

constructor(private alertService: AlertService) {}

update() {
    this.demoService.update(...).subscribe(result => {
      if(result.success.count > 0) {
        result.success.forEach(item => {
           this.alertService.info(item);
           await this.delay(2000);
        }
      }
      if(result.failed.count > 0) { 
         result.failed.forEach(item => {
           this.alertService.error(item);
           await this.delay(2000);
        }
      }
    }, err => {
        this.alertService.error(err.message);
    });
}

function delay(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

For each message, to not be override by the next, you need to await a time as the popup to be hidden. For this delay() function is used.

and the service class as an alert provider (and inject into your component):

import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

@Injectable({
  providedIn: 'root',
})
export class AlertService {
  constructor(private toastr: ToastrService) {}
  public success(message: string): void {
    this.toastr.success(message, '', {
      timeOut: 2000
    });
  }

  public error(message: string): void {
    this.toastr.error(message, '', {
      timeOut: 2000
    });
  }
}
AlleXyS
  • 2,476
  • 2
  • 17
  • 37
  • Thanks for reply, voted up. what about **grouping** `.toPromise()`? I cannot use groupBy with it. Is there any way? –  Feb 16 '21 at 09:41
  • You're welcome. where you need to use groupBy? Please share the `demoService.update()` content – AlleXyS Feb 16 '21 at 09:49
  • Here is the details: [How to merge or groupBy toPromise via RxJs?](https://stackoverflow.com/questions/66222207/how-to-merge-or-groupby-topromise-via-rxjs) –  Feb 16 '21 at 09:59