问题描述
在我的代码中,我有一个按钮,它将浏览数据列表并为每个数据打开一个mat-dialog
。
不幸的是,在循环过程中,所有mat-dialogs
都打开了。
我想通过使用dialogRef.afterClosed()
方法,根据结果(true
)打开下一个mat-dialog
或(false
)循环结束。
openDialog(): void {
this.data.forEach(data => {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog,{
disableClose: true
});
dialogRef.componentInstance.data = data;
dialogRef.afterClosed().subscribe(result => {
if (result) {
// open next mat-dialog
} else {
// stop loop
}
});
});
}
<div mat-dialog-actions>
<button mat-button (click)="_dialogRef.close(true)">Ok</button>
<button mat-button (click)="_dialogRef.close(false)">Cancel</button>
</div>
我该怎么做?我不知道该怎么办。
感谢您的帮助。
解决方法
您可以通过将方法标记为async
并等待对话框afterClosed()
的调用来实现此目的,但是由于await
仅适用于Promise,因此您需要将Observable
转换为Promise
。
这是对我有用的解决方案
@Component({
selector: "dialog-overview-example",templateUrl: "dialog-overview-example.html",styleUrls: ["dialog-overview-example.css"]
})
export class DialogOverviewExample {
data: any[] = DATA;
constructor(public dialog: MatDialog) {}
async openDialog() {
for(var i =0; i < this.data.length; i++) {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog,{
disableClose: true
});
dialogRef.componentInstance.data = this.data[i];
var result = await dialogRef.afterClosed().toPromise();
if (!result) {
console.log("Stop loop",result);
break;
}
// else continue the loop
}
}
}
,
您可以通过rxjs takeWhile来实现
from(this.data)
.pipe(
concatMap(x => {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog,{
disableClose: true
});
dialogRef.componentInstance.data = x;
return dialogRef.afterClosed();
}),takeWhile(Boolean)
).subscribe();
,
我建议不要使用迭代器(foreach)(实际上,我不鼓励使用迭代器),而是如果仍有更多数据需要显示,则再次在订阅中触发openDialog
(类似于队列)方法)。当然,这需要从列表中删除显示的数据,但同时也允许将新数据附加到列表中。