2016-12-25 54 views
1

我正在使用類似於angular2 heros教程的文本搜索功能,但在用戶未搜索時無法隱藏div。我在我的組件下面的代碼:只有在可觀察流爲空時才顯示div

searchLocations: Observable<Location[]>; 
private searchTerms = new Subject<string>(); 

// ... 

ngOnInit(): void { 
    // ... 
    this.searchLocations = this.searchTerms 
     .debounceTime(300) 
     .distinctUntilChanged() 
     .switchMap(term => term 
      ? this.locationSearchService.search(term) 
      : Observable.of<Location[]>([])) 
     .catch(error => { 
      console.error(error); 
      return Observable.of<Location[]>([]); 
     }); 
} 

然後我的HTML中,我顯示用戶的結果與

<div class="results"> 
    <div *ngFor="let loc of searchLocations | async" class="search-result"> 
     {{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }} 
    </div> 
</div> 

但隨着我當前的代碼進行搜索時,results DIV是總是當下。如何檢查可觀察流是否爲空?我試圖.count().length(),但是這兩種也返回觀測....我想我需要做一些事情,如:

<div class="results" *ngIf="???"> 
    <!-- ... --> 
</div> 
+0

可能的,因爲http://stackoverflow.com/questions/38057537/how-to-check-length-of-the-an-observable-array – yurzui

回答

1

在你ngIf指令,你也應該使用異步管,因爲這是可觀測:

<div class="results" *ngIf="!(searchLocations | async)?.length"> 
     <div *ngFor="let loc of searchLocations | async" class="search-result"> 
      {{ loc.name }}, {{ loc.adminName1 }}, {{ loc.countryCode }} 
     </div> 
    </div> 
+0

的請一些評論添加到您的代碼段,以幫助該OP瞭解你的解決方案如何工作 –

+0

這似乎沒有工作,給了我錯誤:無法讀取屬性'長度'null' –

相關問題