2017-04-02 123 views
1

我正試圖在RxJs中使用Observable。我有一個帶有搜索框的頁面,當用戶開始輸入時,Webservice返回20個結果,然後當我按顯示更多然後顯示下一個20結果等。將下一個結果合併爲一個並在Angular 2項目中顯示

我能夠成功獲得前20項成績,但接下來的20項我無法與之前的項目合併。

服務

@Injectable() 
export class AppService { 

constructor(private http : Http) {} 

search(terms : Observable <string>) { 

    return terms 
     .debounceTime(400) 
     .distinctUntilChanged() 
     .switchMap(term => this.searchEntries(term)); 

    } 

searchEntries(term) { 

    const API = "https://jsonplaceholder.typicode.com/posts/"; 

    return this 
     .http 
     .get(API) 
     .map(res => res.json()); 
    } 

} 

組件

export class AppComponent { 

resp : Object; 
searchTerm = new Subject <string>(); 

constructor(private _searchService : AppService) { 
this 
    ._searchService 
    .search(this.searchTerm) 
    .subscribe(results => { 
    this.resp = results; 
    }); 
} 
} 

HTML

<span *ngFor="let res of resp | slice:0:10"> 
     <a href="#" class="lex-column align-items-start"> 
     <div class="d-flex w-100 justify-content-between"> 
      <h5 class="mb-1">{{res.title}}</h5> 
      <small># {{res.id}}</small> 
     </div> 
     <p class="mb-1">{{res.body}}</p> 
     <small >Donec id elit non mi porta.</small> 
     </a> 
</span> 

我公頃已將API網址替換爲一般網址

請將下20個結果與以前顯示的結果合併。

+0

'resp'是一個數組嗎?你如何顯示它?你有沒有檢查http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically? – echonax

+0

它在那裏...互聯網被關閉了一分鐘.. – Gags

+0

而不是分配值如何推它到陣列?例如:'this.resp.push(results);'當然你需要初始化'resp = [];' – echonax

回答

0

您可以使用take(n)操作

return terms 
     .debounceTime(400) 
     .distinctUntilChanged() 
     .take(10) 
     .switchMap(term => this.searchEntries(term)); 

通過這個每次都採取了只有10項。

+0

這需要什麼(10)將有助於實現..它將有助於合併10個結果嗎? – Gags

+0

,這似乎並沒有工作 – Gags

+0

我認爲這將有所幫助。但嘗試其他方法,您可以在訂閱時進行陣列推送。當你嘗試這個時,你會得到什麼?和錯誤? – Aravind