在我的代码中,我有一个按钮,它将浏览数据列表,并为每个数据打开一个mat-dialog。
不幸的是,在循环过程中,所有的mat-dialogs都打开了。
我想要发生的是,通过使用dialogRef.afterClosed()方法,取决于下一个mat-dialog打开的结果(true)或(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>我该怎么做?我不知道该怎么做。
谢谢你的帮助。
发布于 2020-10-21 09:22:03
您可以通过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();发布于 2020-10-21 09:16:31
您可以通过将您的方法标记为async并等待您的对话框afterClosed()调用来实现这一点,但是由于await只适用于承诺,所以需要将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
}
}
}发布于 2020-10-21 09:17:53
我建议不要使用迭代器(foreach) (实际上,我会劝阻使用迭代器),但是如果还需要显示更多的数据(类似队列的方法),则应该在订阅中再次触发openDialog。当然,这需要从列表中删除显示的数据,但同时也允许向其追加新的数据。
https://stackoverflow.com/questions/64460217
复制相似问题