应用程序组件中的prime-ng p-toast不显示从其他组件发送的消息

问题描述 投票:1回答:1

为了减少我的webapp中的primeng toast组件(p-toast)的数量,我尝试在app.component中使用带有键的中央p-toast。然后我使用带有该Toast组件的密钥的messageservice从其他组件添加消息。不幸的是,没有显示祝酒词。

我的app.component.html

<div>
  <app-header></app-header>
  <router-outlet></router-outlet>
  <app-footer *ngIf="!userLoggedIn"></app-footer>
</div>
<p-toast [style]="{ marginTop: '80px' }" key="myToast"></p-toast>

我的app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [MessageService]
})
export class AppComponent implements OnInit, OnDestroy {

  constructor(
    private readonly messageService: MessageService
  ) {...

从组件内部(通过routeroutlet显示)我添加一条消息:

  this.messageService.add({
    severity: 'success',
    summary: 'Success Message',
    key: 'myToast',
    detail: 'Order submitted'
  });

我也尝试了以下替代方案:

this.ngZone.run(() => {
  this.messageService.add({
    severity: 'success',
    summary: 'Success Message',
    key: 'myToast',
    detail: 'Order submitted'
  });
});

setTimeout(() => {
  this.messageService.add({
    severity: 'success',
    summary: 'Success Message',
    key: 'myToast',
    detail: 'Order submitted'
  });
}, 1000);

这些都不起作用。

我忘记了什么吗?或者p-toast是不是意味着像这样使用?

angular primeng
1个回答
0
投票

你只需要改变一些东西

1)将ToastModule添加到AppModule导入列表中

2)将MessageService添加到AppModule提供者列表中

3)从任何其他组件中的providers数组中删除MessageService,您仍然可以导入MessageService并从任何组件执行this.messageService.add

然后尝试一下

© www.soinside.com 2019 - 2024. All rights reserved.