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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With