RxJS 구독() 함수의 구성요소로 선언된 액세스 변수
나는 사용할 수 있다.this.variable
다음과 같은 RxJS 함수 내부를 제외하고 구성 요소의 임의 부분에 있는 변수에 액세스하기 위해subscribe()
또는catch()
.
아래 예에서 프로세스를 실행한 후 메시지를 인쇄하려는 경우:
import {Component, View} from 'angular2/core';
@Component({
selector: 'navigator'
})
@View({
template: './app.component.html',
styles: ['./app.component.css']
})
export class AppComponent {
message: string;
constructor() {
this.message = 'success';
}
doSomething() {
runTheProcess()
.subscribe(function(location) {
console.log(this.message);
});
}
}
내가 달릴 때doSomething()
, 나는 정의가 없다.이 시나리오는 로컬 변수를 사용하여 해결할 수 있다.
import {Component, View} from 'angular2/core';
@Component({
selector: 'navigator'
})
@View({
template: './app.component.html',
styles: ['./app.component.css']
})
export class AppComponent {
message: string;
constructor() {
this.message = 'success';
}
doSomething() {
// assign it to a local variable
let message = this.message;
runTheProcess()
.subscribe(function(location) {
console.log(message);
});
}
}
이 문제는 우리 사회와 관련이 있는 것 같다.this
하지만, 왜 내가 그 웹사이트에 접속할 수 없는가this.message
안쪽에subscribe()
?
이것은 rx나 각, 그리고 Javascript와 Typecript와는 아무 상관이 없다.
의 의미론도 잘 알고 있을 겁니다.this
Javascript의 함수 호출의 맥락에서(만약 그렇지 않다면, 온라인에서 설명의 부족은 없다) - 물론 그러한 의미론들은 첫 번째 조각에 적용되며, 그것이 유일한 이유다.this.message
내면에 정의되지 않다subscribe()
그냥 자바스크립트야
Typecript에 대해 이야기 하고 있으니:화살표 함수는 (부분적으로) 의 의미를 어휘적으로 포착하여 이러한 의미론의 어색함을 회피하기 위해 의도된 Typecript 구성이다.this
, 라는 뜻이다.this
화살표 함수 안. =====this
외부 맥락에서
따라서 교체할 경우:
.subscribe(function(location) {
//this != this from outer context
console.log(this.message); //prints 'undefined'
});
기준:
.subscribe((location) => {
//this == this from the outer context
console.log(this.message); //prints 'success'
});
기대했던 결과를 얻을 수 있을 것이다.
@drewmoore의 대답에 대한 대안으로 외부 기능을 가지려면 다음을 수행하십시오.
.subscribe((location) => dataHandler(location), (error) => errorHandler(error));
....
const dataHandler = (location) => {
...
}
외부화하여errorHandler
기능, 여러 장소에서 사용할 수 있다(예: 가입).(지방) 화살표 기능을 사용함으로써 코드는 '이것' 컨텍스트를 캡처할 것이다(@Drewmoore의 답변에서 설명됨).
부족한 것은 다음과 같은 글을 쓰고 화살 기능처럼 처리해 온 능력이다.다음은 암묵적으로 그 논거를 작동하고 통과시킨다.불행하게도 당신은 AFAIK를 캡처할 수 없다.this
컨텍스트(일반적으로 사용)bind
비록 그것이 코드를 전체적으로 더 장황하게 만들기는 하지만, 이것을 달성하기 위해.
.subscribe(dataHandler, errorHandler);
이건 너무 간결해!그러나 문맥이 요구된다면 아아아스는 작동하지 않을 것이다.
'IT이야기' 카테고리의 다른 글
Python에서 대용량 파일의 라인 수를 저렴하게 얻는 방법 (0) | 2022.04.09 |
---|---|
Python 3의 상대적 가져오기 (0) | 2022.04.09 |
환원 관측 가능에서 여러 작업을 전송하는 방법? (0) | 2022.04.09 |
현재 파일 디렉터리의 전체 경로를 가져오는 방법 (0) | 2022.04.09 |
Ubuntu에서 pip을 통해 python3 버전의 패키지를 설치하는 방법? (0) | 2022.04.09 |