2016-11-20 138 views
1

我試圖在某人使用我的搜索功能搜索某些不會返回數據庫結果的情況下顯示「未找到結果」。我遇到的問題是,「找不到結果」立即打印到屏幕上 - 然後在搜索查詢實際正在評估時消失 - 然後在沒有找到結果的情況下再次出現。換句話說,它應該像它應該那樣工作,除非它應該等到查詢被實際觸發並評估之後纔在屏幕上打印「未找到結果」。從概念上講,做這件事的最好方法是什麼?一方面,我發現我可以使用超時。但那不是直接解決問題。那麼解決這個問題的最好方法是什麼?這是我對函數的代碼:如何在搜索功能中處理「未找到結果」

public get noResultsFound(): boolean 
{ 
    if (this.query && !this._isSearching && !this.hasResults) { 
     return true; 
    } 
} 

這裏是我的視圖代碼:

<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div> 

回答

0

承諾聽起來像你需要:d https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

沿着這個東西線。

search = (paramObj) : Promise<SomeDataClass> => { 
    // Some search logic 
} 

requestSearch() { 
    this.search(null).then((result) => { 
     if (result.length === 0) 
     { 
      //logic for showing 0 results here 
     } 
     else{ 
      // Show result? 
     } 
    }) 
} 

一個更完整的例子看起來有點像這樣。

class example { 
    public someBool = false; 

    public search = (paramObj): Promise<Array<string>> => { 
     this.someBool = !this.someBool; 
     return new Promise<Array<string>>((resolver) => { 
      // This just simulates something taking time. 
      setTimeout(() => { 
       if (this.someBool) { 
        resolver([]); 
       } else { 
        resolver(["hi","there"]); 
       } 
      }, 1000) 
     }); 
    } 

    public requestSearch() { 
     this.search(null).then((result) => { 
      if (result.length === 0) { 
       console.log("empty") 
      } 
      else { 
       console.log(result) 
      } 
     }) 
    } 
} 
0

那麼,到底我是能夠通過使用某種形式的反跳超時,而是通過改變什麼功能是注重解決這個不 - 可以這麼說。通過這種方式處理它,「未找到結果」從未觸發過。這是我最終使用的:

public get noResultsFound(): boolean 
{ 
    if (!Object.isNullOrUndefined(this._results) && this._results.length < 1) { 
     return true; 
    } 
}