Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prime-ng p-toast in app component not displaying messages sent from other components

In order to reduce the amount of primeng toast components (p-toast) in my webapp I tried to use a central p-toast with key in app.component. Then I add messages from other components using the messageservice with the key of that toast component. Unfortunately the toasts are not being shown.

my 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>

my 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
  ) {...

from within a component (shown through routeroutlet) I add a message:

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

I also tried the following alternatives:

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

and

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

None of this works.

Did I forget something? Or is p-toast not ment to be used like that?

like image 779
Ben Avatar asked Apr 24 '19 11:04

Ben


1 Answers

You just need to change a few more things

1) Add ToastModule to the AppModule imports list

2) Add MessageService to the AppModule providers list

3) Remove MessageService from providers array in any other component, you can still import MessageService and do this.messageService.add from any component

Then try it out

like image 109
Hari Pillai Avatar answered Nov 08 '22 12:11

Hari Pillai