![](/img/trans.png)
[英]How to access a variable defined in service class from a component in Angular 9?
[英]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.