我正在尝试使用 <p-toast>
在我的登录页面中,以便在用户登录时显示通知消息。
<p-toast position="top-center" key="tc"></p-toast>
然后在我的组件中声明消息。
ngOnInit() {
// add toasts
this.messageService.addAll([
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
]);
// do other stuff
}
这行不通。为了确认这不是我的 toast 或消息的问题,我将消息放在 onClick()
中。页面上的事件并手动触发它,这确实有效。
如何让 Toasts 在页面加载时触发?
最佳答案
You have to send the messages once the view is initialized.
但是,通过触发 ngAfterViewInit
Hook 中的消息,您可能会得到一个 ExpressionChangedAfterItHasBeenCheckedError
。
以下是避免此错误的解决方案:
第一个解决方案是使用 setTimeout
调用在一切都初始化后发送消息。
Here is a simple Stackblitz example
ngAfterViewInit() {
setTimeout(() => {
this.messageService.addAll([
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
]);
})
}
另一种解决方案是使用 ChangeDetectorRef
( see this article ) 强制更改检测:
constructor(private messageService: MessageService, private cd: ChangeDetectorRef) { }
ngAfterViewInit() {
this.messageService.addAll([
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 1'},
{key: 'tc', severity: 'info', summary: '30 Nov 2020', detail: 'Important message 2'}
]);
this.cd.detectChanges()
}
关于angular - 如何在页面加载时触发 Toast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366173/