请考虑以下方案,在此我要通过一个儿童组件,稍后使用RXJS可观察到的属性更新。
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;
}
为什么我们需要绑定上下文以获取Angular以获取更改?
第三种情况的问题:
// Scenario 3
// Child component is NOT updated properly
this.someService.someObservable.subscribe(this.doSomething)
是,您无法确定this
关键字在此行上包含的doSomething
功能中包含什么:this.fieldPassedToChildComponent = data;
。这实际上取决于subscribe
方法如何调用您的回调。
如果您查看subscribe
的源代码,您可以找到如何调用回调方法,因此可以将this
设置为什么。我的猜测是undefined
。但可能是什么。因此不要使用这种方式。