簡體   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