我正試圖在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個結果與以前顯示的結果合併。
'resp'是一個數組嗎?你如何顯示它?你有沒有檢查http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically? – echonax
它在那裏...互聯網被關閉了一分鐘.. – Gags
而不是分配值如何推它到陣列?例如:'this.resp.push(results);'當然你需要初始化'resp = [];' – echonax