简体   繁体   English

如何在Angular 7中从服务访问组件

[英]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. 我在Angular 7应用程序中使用PrimeNG库,并对它们如何实现功能感到好奇。 I'll try to explain it: 我将尝试解释一下:

One of its components is 'Toast', that shows short messages with a pop-up style, like this: 它的组成部分之一是“ Toast”,它以弹出样式显示短信,如下所示:

在此处输入图片说明

For it to work, you need to define a p-toast component in the template: 为了使其正常工作,您需要在模板中定义p-toast组件:

<p-toast></p-toast>

And provide a global MessageService to show the message, using this method: 并使用以下方法提供全局MessageService来显示消息:

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? 我的问题是,他们如何从MessageService服务的add方法中找到p-toast组件? 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. 例如,我将p-toast插入了app-component.html模板中,并且无论层次结构如何,都可以使用应用程序所有组件中的messageService.add NOTE: I also declare the MessageService in the providers section of the app.module.ts file, to make the service global. 注意:我还在app.module.ts文件的providers部分中声明了MessageService ,以使服务成为全局服务。

I hope it's understandable... thanks! 我希望这是可以理解的...谢谢!

You need to create customize service and subscribe it to show toast. 您需要创建定制服务并将其订阅以显示吐司。 DEMO DEMO

customize-message.service.ts 定制-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 app.component.html

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

app.component.ts 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 another.component.ts

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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