Fel
Fel

Reputation: 4818

How to access a component from a service in Angular 7

I use the PrimeNG library in an Angular 7 application and I'm curious about how they've implemented a feature. I'll try to explain it:

One of its components is 'Toast', that shows short messages with a pop-up style, like this:

enter image description here

For it to work, you need to define a p-toast component in the template:

<p-toast></p-toast>

And provide a global MessageService to show the message, using this method:

this.messageService.add({severity:'success', summary:'Service Message', detail:'Via MessageService'});

My question is, how do they find the p-toast component from the add method in the MessageService service? For example, I have inserted the p-toast in the app-component.html template and I can use the messageService.add from all the components of the application, no matter the hierarchy. NOTE: I also declare the MessageService in the providers section of the app.module.ts file, to make the service global.

I hope it's understandable... thanks!

Upvotes: 1

Views: 1860

Answers (2)

Fel
Fel

Reputation: 4818

As suggested by the answers, each p-toast component has a subscriber of the global service MessageService to receive the messages to be displayed.

Upvotes: 1

phucnh
phucnh

Reputation: 1115

You need to create customize service and subscribe it to show toast. DEMO

customize-message.service.ts

@Injectable()
export class CustomizeMessageService {

  private loaderSubject = new Subject<MessageState>();
  loaderState = this.loaderSubject.asObservable();

  constructor() { }

  show() {
    this.loaderSubject.next(<MessageState>{ show: true });
  }

}

export interface MessageState {
  show: boolean;
}

app.component.html

<p-toast [style]="{marginTop: '80px'}"></p-toast>

app.component.ts

constructor(private messageService: MessageService, private loaderService: CustomizeMessageService) { }

  ngOnInit() {
    this.loaderService.loaderState.subscribe((state: MessageState) => {
      if (state.show) {
      this.messageService.add({severity:'success', summary: 'Success Message', detail:'Order submitted'});
      }
    });
  }

another.component.ts

constructor(private customizeMessageService: CustomizeMessageService) {}
showToast() {
    this.customizeMessageService.show();
}

Upvotes: 1

Related Questions