![](/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.