Javascript 为什么RxJS或角度可观测订阅方法需要上下文?
考虑以下场景,其中我将向子组件传递稍后使用RxJs可观测订阅更新的属性 Angular在不发送匿名函数或不在该上下文中进行编辑时,不会检测到更改Javascript 为什么RxJS或角度可观测订阅方法需要上下文?,javascript,angular,rxjs,Javascript,Angular,Rxjs,考虑以下场景,其中我将向子组件传递稍后使用RxJs可观测订阅更新的属性 Angular在不发送匿名函数或不在该上下文中进行编辑时,不会检测到更改 // Scenario 1 // Child component IS updated properly this.someService.someObservable.subscribe((data) => { this.doSomething(data); }) // Scenario 2 // Child component IS
// 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;
}
为什么我们需要为angular绑定上下文以获取更改?第三种情况的问题:
// Scenario 3
// Child component is NOT updated properly
this.someService.someObservable.subscribe(this.doSomething)
您无法确定这一行的doSomething
函数中包含的关键字是什么:this.fieldPassedToChildComponent=data代码>。这实际上取决于subscribe
方法调用回调的方式
如果查看subscribe
的源代码,您可以找到回调方法是如何调用的,因此this
设置为什么。我猜是未定义
。但可能是任何东西。因此,不要使用这种方式。如果不使用,则doSomething
中的this
将计算为全局对象。您的意思是场景2有效,但场景3无效?这是有道理的,因为这个是如何工作的除非绑定函数,否则调用函数时将决定此
。@elclars如果您是对的,请编辑它这可能是重复的,因为这是一个非常常见的问题@是的,我只是想知道为什么需要这个上下文,为什么我不能把我的函数作为第一个参数传递。