Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按角度顺序显示toastr消息_Javascript_Angular_Rxjs_Angular Material_Toastr - Fatal编程技术网

Javascript 按角度顺序显示toastr消息

Javascript 按角度顺序显示toastr消息,javascript,angular,rxjs,angular-material,toastr,Javascript,Angular,Rxjs,Angular Material,Toastr,我使用以下更新方法更新多个记录,并从结果接收更新和失败的记录计数。然后我想使用角度材质toastr按顺序显示相关的toastr消息。但是,以下方法跳过了#1中的成功(或者在错误的后面显示),而在#2中显示错误。那么,对于这种方法,我如何按顺序显示它们呢?也许我需要为此使用RxJs update() { this.demoService.update(...).toPromise() .then(result => { if(result.success.coun

我使用以下更新方法更新多个记录,并从结果接收更新和失败的记录计数。然后我想使用角度材质toastr按顺序显示相关的toastr消息。但是,以下方法跳过了#1中的成功(或者在错误的后面显示),而在#2中显示错误。那么,对于这种方法,我如何按顺序显示它们呢?也许我需要为此使用RxJs

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
    });
}

如果您使用Angular:d,您确实需要使用
Rxjs Observables
而不是
Promises

因此,您的代码将成为:

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));
}
对于每一条消息,为了不被下一条消息覆盖,您需要等待一段时间来隐藏弹出窗口。为此,使用了
delay()
函数

以及作为警报提供程序的服务类(并注入到组件中):


谢谢你的回复,投票通过了。分组
.toPromise()
怎么样?我不能将groupBy与它一起使用。有什么办法吗?不客气。您需要在哪里使用groupBy?请共享
demoService.update()
content以下是详细信息:
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
    });
  }
}