简体   繁体   中英

Why does RxJS or Angular Observable subscribe method needs context?

Consider the following scenarios, where I'm passing a child Component a property updated later using a subscription to an RxJs Observable.

Angular is not detecting changes when not sending an anonymous function or biding the this context.

// 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;
}

Why do we need to bind the context for angular to pick up the changes?

The problem with third case:

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

is that you cannot be sure what this keyword contains in your doSomething function on this line: this.fieldPassedToChildComponent = data; . It really depends how subscribe method calls your callback.

If you take a look in source code of subscribe you could find how the callback method is called and therefore what this is set to. My guess would be undefined . But could be anything. Therefore don't use this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM