簡體   English   中英

為什么RxJS或Angular Observable訂閱方法需要上下文?

[英]Why does RxJS or Angular Observable subscribe method needs context?

請考慮以下情形,其中我向子組件傳遞了一個屬性,該屬性以后使用對RxJs Observable的訂閱進行更新。

當不發送匿名函數或投標此上下文時,Angular不會檢測到更改。

// Scenario 1
// Child component IS updated properly
this.someService.someObservable.subscribe((data) => {
    this.doSomething(data);
})

// Scenario 2
// Child component IS updated properly
this.someService.someObservable.subscribe(this.doSomething.bind(this))

// Scenario 3
// Child component is NOT updated properly
this.someService.someObservable.subscribe(this.doSomething)


private doSomething(data) {
    // this is executed on all the scenarios
    this.fieldPassedToChildComponent = data;
}

為什么我們需要綁定角度的上下文來獲取更改?

第三種情況的問題:

// Scenario 3
// Child component is NOT updated properly
this.someService.someObservable.subscribe(this.doSomething)

是您不確定在此行的doSomething函數中this關鍵字包含什么: this.fieldPassedToChildComponent = data; 這實際上取決於subscribe方法如何調用您的回調。

如果你參加的源代碼看看subscribe你能找到的回調方法是如何被調用,因此什么this設置為。 我的猜測是undefined 但是可以是任何東西。 因此不要使用這種方式。

暫無
暫無

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

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