我正在尝试使用ngx-pagination但面临一些问题。我对角度2很新,对于可观察者和订阅者并不了解。
我有一个服务,它会进行http调用并返回数据:
getData(path: string, page: number=1) : Promise<IData[]> {
return this.http.get(path+'&pageNumber='+page)
.toPromise()
.then(response => {
return response.json() as IData[];
});
}
我在我的组件中使用了这些数据:
getDataValues(page: number) {
this.loading = true;
this.asyncData = this.getAsyncData(this.queryPath, page)
.do(res => {
this.total = res.total;
this.p = page;
this.loading = false;
})
.map(res => res.items);
}
getAsyncData(path: string, page: number): Observable<any> {
return Observable
.of({
items: this.repository.getData(path, page),
total: this.dataValues.length
});
}
我的模板看起来像这样:
<div class="list">
<div>
<article class="entity" *ngFor="let data of asyncData | async | paginate: { id: 'server', itemsPerPage: 10, currentPage: p, totalItems: total }">
</article>
</div>
<pagination-controls (pageChange)="getDataValues($event)" id="server"></pagination-controls>
我知道这是不正确的,因为我需要等待承诺解决,但我不知道该怎么做。 ngx-pagination需要Observable,因此asyncData
需要Observable
答案 0 :(得分:0)
如果你看一下旧Angular http服务的'get'方法的类型签名(你正在使用的那个,新的一个叫做HttpClient),你会看到它返回一个Observable类型'Response ”。
get(url: string, options?: RequestOptionsArgs): Observable<Response>;
因此,只需从get调用中删除.toPromise()和.then方法,就可以使用Observable。