여기서 문제는 this
이이 퍼즐의 다른 조각들로 처리되는 방법입니다. 타이프 라이터 컴파일러는 다음과 같은 자바 스크립트를 생성합니다 : .map()
연산자가 수행 extractFeeds()
함수를 호출 할 때
YourComponent.prototype.getFeedContent = function (url) {
return this.http.get(url)
.map(this.extractFeeds)
.catch(this.handleError);
};
YourComponent.prototype.extractFeeds = function (res) {
var content = res.text;
var feed = this.extractItems(content);
return feed;
};
YourComponent.prototype.extractItems = function (content) {
console.log(content);
var f = this.getFeedInfo(content);
return {
status: 'ok',
feed: f,
items: this.getItems(content.toString(), 'item')
.concat(this.getItems(content.toString(), 'entry'))
};
};
지금,이 코드의 주요주의해야 할 점은 그 this.http.get()
호출에 의해 반환 된 관찰 가능한, 하지의 맥락에서 구성 요소 컨텍스트에서. 따라서 extractFeeds()
함수 this
이 Observable을 가리키고, this.extractItems()
을 호출하려고하면 Observable에 그러한 메서드가 없으므로 분명히 실패합니다.
따라서 수정하는 것은 실제로 매우 간단합니다.
var YourComponent = (function() {
function YourComponent(http) {
var _this = this;
this.http = http;
this.extractFeeds = function (res) { // this is how it is defined now in JS
var content = res.text;
var feed = _this.extractItems(content);
return feed;
};
}
// ... rest declarations skipped
return YourComponent;
}());
TSC 여기에 무슨 짓을했는지 참조 :
getFeedContent(url: string): Observable<Feed> {
return this.http.get(url)
.map(this.extractFeeds)
.catch(this.handleError);
}
private extractFeeds = (res: Response) => { // <-- using arrow syntax
let content = res.text;
let feed = this.extractItems(content);
return feed ;
}
private extractItems(content) : Feed {
console.log(content);
let f = this.getFeedInfo(content);
return {
status: "ok",
feed : f ,
items: this.getItems(content.toString(), 'item')
.concat(this.getItems(content.toString(), 'entry'))
}
}
이 시간 타이프 라이터 컴파일러는 다음과 같은 코드를 생성합니다 : 당신이해야 할 일은 다음과 같이) (선언을 extractFeeds을 변경하는 것입니다?구성 요소에 대한 참조를 _this
변수로 보존하고 함수를 extractFeeds()
내부로 호출하는 데 사용했습니다. 이런 식으로 this
코드의 Typescript 버전의 포인터는 항상extractFeeds()
내부의 구성 요소 인스턴스를 가리키고 함수는 this
이 실제 자바 스크립트 코드를 가리키고 있습니다.
같은 방법으로 호출되는 다른 모든 함수 (예 : 코드에서 handleError)로 이동합니다.
this
에 대한 자세한 설명은 Typescript here에서 찾을 수 있습니다.
동일한 오류가 표시되는 것과 함께 큰 그림을 얻을 수 있다면 디버깅을 더 잘 수행 할 수 있습니다. 피드가 비어 있어도 – rjustin