2017-12-29 24 views
0

RxJs Observable에 대한 구독을 사용하여 나중에 업데이트되는 하위 구성 요소를 전달하는 다음 시나리오를 고려하십시오.RxJS 또는 Angular 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; 
} 

왜 변경 사항을 적용하기 위해 각도 용 컨텍스트를 바인딩해야합니까?

+0

doSomething 내부의'this'는 전역 객체를 평가합니다. –

+0

시나리오 2는 작동하지만 3은 작동하지 않는다는 것을 의미합니까? 이것이 '이'가 어떻게 작동하는지 이해하기 때문에. 'this'는 함수를 호출 할 때 결정됩니다. – elclanrs

+0

@elclanrs 당신이 맞아서 편집했습니다 –

답변

1

세 번째 경우의 문제 : this.fieldPassedToChildComponent = data; :

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

this 키워드가이 라인에 doSomething 기능에 포함 된 내용을 확신 할 수 없다는 것입니다. subscribe 메서드가 콜백을 호출하는 방법에 따라 다릅니다.

subscribe 소스 코드를 보면 콜백 메서드가 호출되는 방식을 알 수 있으며 따라서 this은 무엇으로 설정되어 있는지 확인할 수 있습니다. 내 추측은 undefined 일 것입니다. 그러나 무엇이든 될 수 있습니다. 따라서이 방법을 사용하지 마십시오.