【发布时间】:2021-07-24 15:25:35
【问题描述】:
我在我的 Angular 项目中创建了一个模态作为单独的组件,如下所示:
HTML:
<div mat-dialog-title>
{{title}}
</div>
<div mat-dialog-content>
<p>{{message}}</p>
</div>
<div mat-dialog-actions>
<button mat-button color="primary" (click)="confirm()">{{btnOkText}}</button>
<button mat-button (click)="decline()" cdkFocusInitial>{{btnCancelText}}</button>
</div>
TS:
export class ConfirmDialogComponent implements OnInit {
title!: string;
message!: string;
btnOkText!: string;
btnCancelText!: string;
constructor(
public dialogRef: MatDialogRef<ConfirmDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: ConfirmDialogModel) {
// Update view with given values
this.title = data.title;
this.message = data.message;
this.btnOkText = data.btnOkText;
this.btnCancelText = data.btnCancelText;
}
ngOnInit(): void {
}
confirm() {
// Close the dialog, return true
this.dialogRef.close(true);
}
decline() {
// Close the dialog, return false
this.dialogRef.close(false);
}
}
/**
* Class to represent confirm dialog model.
*
* It has been kept here to keep it as part of shared component.
*/
export class ConfirmDialogModel {
constructor(
public title: string,
public message: string,
public btnOkText: string,
public btnCancelText: string) {
}
}
我创建了一个根注入服务并放入一个初始化并打开对话框的方法,如下所示:
confirmDialog(): void {
const title = 'Confirmation';
const message = 'Are you sure you want to do this?';
const btnOkText = 'Ok';
const btnCancelText = 'Cancel';
const dialogData = new ConfirmDialogModel(title, message, btnOkText, btnCancelText);
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
maxWidth: "400px",
data: dialogData
});
dialogRef.afterClosed().subscribe(dialogResult => {
dialogResult;
});
}
如果我console.log(dialogResult)我会得到正确的结果(真/假)
所有这一切都很好,但是,我想将这个 dialogResult 变成一个可观察的对象,任何组件都会调用我的确认服务,看到 dialogResult 然后基于它执行操作。
例子:
我有一个 home 组件,我将 confirmService 注入其中
constructor(private confirmService : ConfirmService) {}
然后,在 home.html 中,我创建了一个带有 (click) 事件的按钮,如下所示:
<button mat-raised-button color="primary" (click)="confirm()">Confirm</button>
confirm()函数如下:
confirm() {
this.confirmService.confirmDialog();
}
我希望能够订阅confirmDialog() 并从中获取结果,我该怎么做?
【问题讨论】: