我想声明一个应用程序范围(即:在app.component.html内),然后能够通过从任何组件或任何服务调用ConfirmationService.confirm()来显示它。
这种情况可能吗?
我尝试将其添加到app.component.html 代码:
<p-confirmDialog key="mainDialog" class="styleDialog" [baseZIndex]="10000"></p-confirmDialog>
然后从服务中调用它 代码:全选
@Injectable({
providedIn: 'root',
})
export class FooService{
constructor(
private confirmationService: ConfirmationService,
) {}
doSomeStuff() {
...
this.confirmationService.confirm({
key:'mainDialog',
message: 'some message',
header: 'Warning',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'ok',
rejectVisible: false,
accept: () => {},
});
}
}
但这没有任何作用。
我错过了什么吗?这是受支持的场景吗?或者我是否需要实现自己的“对话即服务”机制?
谢谢
在之前的 Angular 13 项目中,我可以在任何组件中注入 PrimeNg ConfirmationService(或 MessageService),它会显示我的 app.component.html 中的组件。 使用 Angular 17 启动一个新项目,这不再起作用了。我想由于 NgModules 已被删除,PrimeNg 服务不再是单例,任何注入都会返回一个新实例。
为了解决这个问题,我围绕 PrimeNg 和ConfirmationService 构建了一个包装器。
1° 确认-dialog-wrapper.service.ts
providedIn: 'root'
确保我这次使用的是单身人士。请参阅https://angular.io/guide/singleton-services。
@Injectable({
providedIn: 'root',
})
export class ConfirmDialogWrapperService {
private _confirmationSubject: Subject<Confirmation> = new Subject();
public readonly confirmationSubject: Observable<Confirmation> = this._confirmationSubject.asObservable();
public confirm(confirmation: Confirmation): void {
this._confirmationSubject.next(confirmation)
}
}
2°确认-dialog-wrapper.component.html
<p-confirmDialog>
<ng-template pTemplate="footer">
<p-button label="Confirm" (click)="confirm()"></p-button>
<p-button label="Cancel" (click)="reject()"></p-button>
</ng-template>
</p-confirmDialog>
3° 确认-dialog-wrapper.component.ts 请注意
?.()
语法,因为接受和拒绝可能是未定义的。
@Component({
selector: 'confirm-dialog-wrapper',
standalone: true,
imports: [ConfirmDialogModule],
providers: [ConfirmationService],
templateUrl: './confirm-dialog-wrapper.component.html'
})
export class ConfirmDialogWrapperComponent {
confirmation: Confirmation | undefined;
constructor(
public confirmationService: ConfirmationService,
private confirmationService: ConfirmDialogWrapperService) {
confirmationService.confirmationSubject
.subscribe((confirmation: Confirmation): void => {
this.confirmation = confirmation
confirmationService.confirm(confirmation)
})
}
confirm() {
this.confirmation?.accept?.()
this.confirmationService.close()
}
reject() {
this.confirmation?.reject?.()
this.confirmationService.close()
}
}
4°app.component.html
<router-outlet></router-outlet>
<confirm-dialog-wrapper></confirm-dialog-wrapper>
5° 现在我只需要调用ConfirmDialogWrapperService 的confirm() 方法,它接受常规的PrimeNg 确认对象。下面的例子
this.confirmDialogWrapperService.confirm({
message: "Please confirm you wish to delete this stuff",
accept: () => {this.delete(this.stuff)}
})