2017-09-20 8 views
0

좋아, 나는 RxJs에 새로 왔어. 오늘 소개 되었어. 이건 완전히 새로운 질문이다.Angular2 Observable Rxjs 개인 기능을 호출하는 방법

내 유스 케이스는 XML RSS 피드를 추출하여 JSON 피드로 변환하는 것이다.

나는 다음과 같은

getFeedContent(url: string) : Observable<Feed> { 
    return this.http.get(url) 
     .map(this.extractFeeds) 
     .catch(this.handleError); 
} 

private extractFeeds(res: Response) { 
    let content = res.text; 
    let feed = this.extractItems(content); 
    return feed ; 
} 

추출물 항목은 콘텐츠에 takens와 XML은 JSON 개체를 구축하는 분석 수행하는 일반 함수가있는 FeedService 있습니다.

feed.service.ts : 144 this.extractItems 아닌되어 여러 다른 방법

다음

코드

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')) 
    } 
} 

이 코드를 실행할 때이 오류가 무엇입니까가되어 있습니다 함수

Observables를 정규 함수 호출로 혼합했을 수 있습니다. 도움이 필요합니다. XML 내용을 입력으로하여 extractItems를 호출하는 방법.

감사합니다.

+0

동일한 오류가 표시되는 것과 함께 큰 그림을 얻을 수 있다면 디버깅을 더 잘 수행 할 수 있습니다. 피드가 비어 있어도 – rjustin

답변

0

이 문제는 'this'컨텍스트에서 비롯됩니다. this.extractItems()를 사용할 때 'this'의 컨텍스트는 클래스가 아닌 관찰 가능 범위 내에 있습니다. 이 같은

시도 뭔가 :

let extractFeeds = (res: Response) => { 
    let content = res.text; 
    let feed = this.extractItems(content); 
    return feed; 
} 

당신은뿐만 아니라 rxjs에서 수입해야 할 수도 있습니다.

화살표 표기법을 사용하면 관찰 대상에 대한 '이'컨텍스트가없고 클래스 내의 호출 메서드가 작동합니다.

+0

"this.extractItems가 함수가 아닙니다."라는 동일한 오류 메시지가 없습니다. –

+0

extractFeeds 함수 서명을 private extractFeeds (res : Response)로 변경했습니다. Observable ... 도움이되지 않았습니다. –

+0

@RajeshJain 코드를 업데이트하면 해당 샷이 제공됩니다. – rjustin

2

여기서 문제는 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에서 찾을 수 있습니다.

+0

자세한 답변을 보내 주셔서 감사합니다. 사소한 조정 임에도 불구하고 res.text에 encodingHint를 제공해야했습니다. let content = res.text ("iso-8859"); –

+0

@RajeshJain, 도와 줘서 기쁩니다. 그것이 효과가 있다면 대답을 받아주십시오. 그리고 더 행운을 빕니다 Typescript + Angular4 학습! :) –