问题描述
我使用以下更新方法更新多个记录,并从结果中接收更新和失败的记录计数。然后我想使用 Angular Material 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,你肯定需要使用 Rxjs Observables
而不是 Promises
:d
因此,您的代码将变为:
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()
函数。
和作为警报提供者的服务类(并注入到您的组件中):
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
});
}
}