news.html
刷新功能
<ion-refresher (ionRefresh)="doRefresh($event)">
<ion-refresher-content pullingText="pull to refresh">
</ion-refresher-content>
</ion-refresher>
从服务器获取新闻列表
<ion-list *ngSwitchCase="'news'">
<ion-card>
<ion-item-group (click)="goToNewsDetail(new)" text-wrap *ngFor="let new of news">
<ion-thumbnail *ngIf="new.Preview_image1" item-start>
<img src="{{new.Preview_image1}}">
</ion-thumbnail>
<ion-card-content>
<ion-item>
<ion-card-title>{{new.title}}</ion-card-title>
<p>{{new.news_category}}</p>
<h3>{{new.publish_time}}</h3>
</ion-item>
</ion-card-content>
</ion-item-group>
</ion-card>
</ion-list>
news.ts
doRefresh(refresher){
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 1500);
}
获取新闻数据
constructor(public navCtrl: NavController,
public navParams: NavParams,
public newsData:NewsDataProvider){
this.getNews();
}
getNews() {
this.newsData.getNews().then(data => {
this.news = data;
});
}
我想刷新新闻列表并从服务器获取新的新闻列表。这段代码我来自ionic2 doc,但它不适用于我
编辑: 这是我在 news.ts 中添加的内容,没有显示错误,但在刷新后没有新闻列表出现。
doRefresh(refresher){
this.getNews().then(() => {
refresher.complete();
});
}
getNews(): Promise<any> {
return this.newsData.getNews().then(data => {
this.news = data;
});
}
答案 0 :(得分:1)
您是否已尝试过调用getNews
doRefresh?
方法
constructor(public navCtrl: NavController,
public navParams: NavParams,
public newsData: NewsDataProvider){
this.getNews();
}
getNews(): Promise<any> {
return this.newsData.getNews().then(data => {
this.news = data;
});
}
doRefresh(refresher) {
this.getNews().then(() => {
refresher.complete();
});
}
修改强>
调试代码后,我们发现该服务保留了数据的本地副本:
getNews() {
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('servertrj.com/api/news/index/…').map(res => res.json().data).subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
这就是为什么当刷新刷新试图获取新数据时,服务返回相同的项目列表。用以下方法替换该方法应该有效:
getNews() {
return new Promise(resolve => {
this.http.get('servertrj.com/api/news/index/…').map(res => res.json().data).subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
或者不是像这样创建新的承诺,而是可以使用RxJS中的toPromise
运算符:
getNews(): Promise<any> {
return this.http.get('servertrj.com/api/news/index/…')
.map(res => res.json().data)
.toPromise();
}