PrimeNG Message & Toast worked in Component but not in Service

Viewed 5368

I have a working message alert in component using PrimeNG framework.

@Component

@Component({
    selector: 'app-client',
    templateUrl: './client.component.html',
    styleUrls: ['./client.component.css'],
    providers: [MessageService],
})

Constructor

private msg: MessageService,

Component method

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

But once i moved to a service's method and include the 'ClientService' in component

import { ClientService } from '../../../shared/services/client.service'

Import message in client.service.ts

import { MessageService } from 'primeng/api';
...

@Injectable({
  providedIn: 'root'
})

method in ClientService

...
this.msg.add({severity:'success', summary:'Success', detail: msg});
...

There ain't any error messages, also no toast prompt. I tried to understand the official doc https://www.primefaces.org/primeng/showcase/#/toast

A message is displayed using a MessageService, make sure your component has an injectable MessageService defined as a provider otherwise Toast cannot be utilized.

But i have no idea how to 'inject' messageservice.

sample project here https://stackblitz.com/edit/d-toast

2 Answers

injecting just means in your ClientService you should have this:

constructor(private messageService: MessageService) {}

and in your component you should add ClientService in the providers array

You have to pass messageservice from component and use it into service.

app.component.ts

constructor(private toastService: ToastService) {}

this.toastService.ShowMessage(this).subscribe(() => {});

client-service.ts

ShowMessage(instance: any){
  instance.toastService.ShowToast();
}

toast-service.ts

constructor(private messageService: MessageService) {}

ShowToast(){
   this.messageService.add({severity:'success', summary:'Success', detail: msg});
}
Related