2016-11-18 2 views
1

RXJS 디 바운싱을 사용한 간단한 검색 방법이 있습니다.서비스에서 오류 발생 후 변경 방법이 호출되지 않습니다.

이렇게하면됩니다.

this.searchTerm.valueChanges 
     .debounceTime(this._debounceDelay, this._scheduler) 
     .distinctUntilChanged() 
     .filter(this.filterForBlank.bind(this)) 
     .filter(this.filterForLength.bind(this)) 
     .switchMap(term => this.searchService.serchBy(term)) 
     .subscribe((data) => { 
     // do something 
     }, (err) => { 
      // show error on UI 
     }); 




private filterForLength(term: string) { 
    return (term.trim().length > 2); 
    } 

    private filterForBlank(term: string) { 
    if (isEmpty(term)) { 
       return false; 
    } 
    return true; 
    } 

하지만 오류가있는 경우 (예 : URL을 잘못된 것으로 변경 한 경우 ...이 변경 기능이 다시 작동하지 않음) 심지어 값을 변경 한 후에도

나는 오류가 있으면 관찰 할 수 없게 죽일 필요가 있다고 생각합니다. 그러나 정확하게 이것을 달성하는 방법을 모르십시오.

답변

0

귀하의 설명이 거의 정확합니다. 오류를 포착하지 않고 관찰 가능한 오류를 발생 시키면 더 이상 작동하지 않습니다. 당신이해야 할 일은 catch 연산자를 사용하여 오류를 잡아 내고 관측 대상을 '죽이는'일없이 오류를 처리하는 것입니다.

이는 다음과 같이 수 : 당신이 백엔드 호출이 실패라면 이제

this.searchTerm.valueChanges 
    .debounceTime(this._debounceDelay, this._scheduler) 
    .distinctUntilChanged() 
    .filter(this.filterForBlank.bind(this)) 
    .filter(this.filterForLength.bind(this)) 
    .switchMap(term => this.searchService.serchBy(term)) 
    .catch(errors => { 
    return Rx.Observable.empty(); 
    }); 
    .subscribe((data) => { 
    // do something 
    }); 

, 그것은 정상적으로 캐치 조항에 의해 처리 될 것이며, 새로운 빈 값을 반환합니다. 이 빈 값을 사용하여 성공했을 때 표시 할 데이터를 지울 수 있습니다. 작동하면 catch 절을 건너 뜁니다.

편집 : 정확합니다. 이것은 작동하지 않습니다. 관찰 가능한 체인 오류가 발생하면 체인 전체가 손상된다는 사실 때문에. 이 문제를 해결하려면, 당신은이 작업을 수행 할 필요가 :

this.searchTerm.valueChanges 
    .debounceTime(this._debounceDelay, this._scheduler) 
    .distinctUntilChanged() 
    .filter(this.filterForBlank.bind(this)) 
    .filter(this.filterForLength.bind(this)) 
    .switchMap(term => 
       this.searchService.serchBy(term) 
        .catch(errors => { 
          // show error on ui 
          return Rx.Observable.empty() 
        })) 
    .subscribe((data) => { 
    // do something 
    }); 

switchMap 내부의 catch 문을 이동함으로써, 휴식 것이다 switchMap 내부의 관찰 체인 될 것입니다. 그러나 'this.searchTerm.valueChanges'에서 시작하여 원래 체인은 중단되지 않고 유지됩니다.

오답에 대해 사과드립니다.

+0

작동하지 않습니다! 잡으려고하지만 값을 변경 한 후에 다시 API를 호출하지 않습니다. –

관련 문제