繁体   English   中英

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

[英]How to access a component from a service in Angular 7

我在Angular 7应用程序中使用PrimeNG库,并对它们如何实现功能感到好奇。 我将尝试解释一下:

它的组成部分之一是“ Toast”,它以弹出样式显示短信,如下所示:

在此处输入图片说明

为了使其正常工作,您需要在模板中定义p-toast组件:

<p-toast></p-toast>

并使用以下方法提供全局MessageService来显示消息:

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

我的问题是,他们如何从MessageService服务的add方法中找到p-toast组件? 例如,我将p-toast插入了app-component.html模板中,并且无论层次结构如何,都可以使用应用程序所有组件中的messageService.add 注意:我还在app.module.ts文件的providers部分中声明了MessageService ,以使服务成为全局服务。

我希望这是可以理解的...谢谢!

您需要创建定制服务并将其订阅以显示吐司。 DEMO

定制-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的订户,以接收要显示的消息。

暂无
暂无

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

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