简体   繁体   中英

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:

在此处输入图片说明

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!

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();
}

如答案所示,每个p-toast组件都有一个全局服务MessageService的订户,以接收要显示的消息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM