2017-06-20 25 views
1

我不完全知道什麼是錯的,但我試圖從angular doc申請搜索系統沒有成功。Angular:Observable不工作

以下是該組件所使用的功能:

// my-comp.component.ts 
public testing: Observable<any>; 
private searchTerms = new Subject<string>(); 

search(term: string): void { 
    this.searchTerms.next(term.toUpperCase()); 
} 

此功能每一個我在搜索框所以沒有問題就在這裏輸入一些時間擊中。

這裏是ngOnInit方法:

// my-comp.component.ts 
ngOnInit(): void { 

    this.testing = this.searchTerms 
     .debounceTime(300)  // wait 300ms after each keystroke before considering the term 
     .distinctUntilChanged() // ignore if next search term is same as previous 
     .switchMap(term => term // switch to new observable each time the term changes 
      // return the http search observable 
      ? this.refundCaseService.search(term) 
      // or the observable of empty heroes if there was no search term 
      : this.test(term) 
     ) 
     .catch(error => { 
      // TODO: add real error handling 
      console.log(error); 
      return Observable.of<any>(); 
     }); 

} 

test(term: string) { 
    console.log(term); 
    return Observable.of<any>(); 
} 

永遠達不到這個代碼,它不進入服務既不是測試功能(我用的斷點和執行console.log確保)。

我不明白這是如何工作的。

使用: 角4.0.0 角CLI 1.0.6

+0

所以你訂閱somehwere this.testing? – chrigu

回答

3

其他答案是正確的,這確實是一個冷觀察。然而,這實際上工作的原因是Angular的async管道。

是在例子中使用的async管:

<div id="search-component"> 
    <h4>Hero Search</h4> 
    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" /> 
    <div> 
    <div *ngFor="let hero of heroes | async" 
     (click)="gotoDetail(hero)" class="search-result" > 
     {{hero.name}} 
    </div> 
    </div> 
</div> 

,因爲這個管道這個例子是工作的。

異步管道訂閱Observable或Promise並返回它發出的最新值。發出新值時,異步管道會標記要檢查更改的組件。當組件被破壞時,異步管道會自動取消訂閱,以避免潛在的內存泄漏。

來源:https://angular.io/api/common/AsyncPipe


TL;博士:,因爲它在模板/ HTML正在處理,你不能調試代碼。

+0

好吧現在我明白好多了,謝謝 – Robouste

+0

@Robouste很高興我能幫忙:-) – echonax

1

你要訂閱可觀察到,否則不「聽」的變化。

this.testing.subscribe(
     x => console.log('onNext: %s', x), 
     e => console.log('onError: %s', e), 
     () => console.log('onCompleted') 
    ); 
+0

當我這樣做時,我'無法讀取'未定義'屬性'訂閱'。我應該把它放在哪裏才能使它工作?感謝@echonax我知道我可以通過異步管道進行訂閱,但是如何在組件內部執行操作? – Robouste

+1

@Robouste你可以在定義'this.testing ='之後做到這一點 – echonax

+0

我覺得很蠢,謝謝。我認爲這是異步的,但它不是 – Robouste

1

查看Christoph Burgdorf的優秀文章THOUGHTRAM - Cold vs Hot Observables

基本上,你在這裏處理的是Cold Observable

冷觀測開始認購時運行,即,可觀察 序列只是開始推值觀察員當訂閱是 調用。 (...)這與熱點觀察值不同,例如鼠標移動 事件或股票代碼,即使在 訂閱處於活動狀態之前,它們已經在生成值。

所以,除非你訂閱this.testing或在你的模板使用async管,不要求將被解僱。