簡體   English   中英

如何捕獲從另一個組件發出的組件中的事件?

[英]How can i capture an event in a component which is emitted from another component?

我想捕獲從另一個組件發出的事件的組件中的事件。

我做了以下代碼

myservice.ts

private _event = new EventEmitter<any>();

get event(): EventEmitter<any> {
  return this._event;
}

mycomponent_2.ts

this.myservice.event.emit(true);

mycomponent_1.ts - 在 ngOnInit() 中添加以下代碼

this.myservice.event.subscribe((value) =>  {
  console.log(value);
});

未打印預期的控制台日志。 看起來該事件未在 component_2 中捕獲

我該如何解決這個問題? 我是否需要將代碼移動到其他一些生命周期鈎子?

您應該使用ReplaySubject以便它發出先前發出的值。 EventEmitter 在它們發出后丟失任何值。

如果服務嘗試在創建組件之前發出值,則除非您使用緩沖主題之一,否則該值將丟失。

private _event = new ReplaySubject<any>(1);

get event(): EventEmitter<any> {
  return this._event;
}

還有BehaviorSubject允許您定義在第一次調用next()之前發出的默認值。

使用Subject :一個 Subject 就像一個 Observable,但可以多播給許多觀察者。 主題就像 EventEmitters:它們維護着許多偵聽器的注冊表。

   @Injectable({
    providedIn: 'root',
})
export class YourService {

    private yourVariable: Subject<any> = new Subject<any>();


    public listenYourVariable() {
        return this.yourVariable.asObservable();

    }


    public yourVariableObserver(value : type) {
        this.yourVariable.next(value);
    }

您可以在您想要使用此服務的地方導入您的組件

import{ YourService } from ...

在您要編寫數據調用的組件中

this.yourService.yourVariableObserver(yourData);

而你想要讀取數據的地方:

  this.yourService.listenYourVariable().subscribe(
        variable => {
          this.data = variable;
        }

)

如果要使用事件,請繼續閱讀。 我創建了一個 repo 並通過向事件添加 @output 來使其工作,如下所示:

export class MyServiceService {
@Output() event = new EventEmitter<any>();

constructor() {}

}

然后為了確保沒有計時問題,我創建了一個按鈕來在一個組件中添加偵聽器,並創建另一個按鈕來觸發事件。 因此我認為主要的錯誤是缺少 @Output 裝飾器。

首選之一是BehaviorSubject 在這里,一個服務可用於在 2 個組件之間共享數據。

當組件彼此不相關時,它非常有用。

例如:服務:StringService

private testString=new BehaviorSubject<string>("Test") //Default value can be passed
public stringValue=this.testString.asObservable();


  passStringChange(project:string){
    this.testString.next(project)
  }

組件 1:

str:string

clickHere(){
this.stringService.passStringChange(str)
}

組件 2:

stringObtained:string
this.stringService.stringValue.subscribe(message=>this.stringObtained=message)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM