我想保留ionic2中服务的数据。现在,每次从API加载数据时,我都不想在每次用户进入视图时调用。
public getUpcomingShoots(){
var json = JSON.stringify({ });
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
return this.http.post(url, json, options)
.map(data => data.json());
}
我的功能是:
getUpcomingShoots (){
this.showLoading();
this.mainService.getUpcomingShoots().subscribe(success => {
if(success.status == 1){
this.loading.dismiss();
console.log(success);
if(success.data.length == 0 ){
this.noUpcomingEvents = true;
}else{
this.noUpcomingEvents = false;
}
this.upcomingEvents = success.data;
}else{
this.loading.dismiss();
console.log(success);
}
},
error => {
console.log( error);
});
}
答案 0 :(得分:0)
这取决于你想要什么。现在,每次用户打开视图时都会获取数据。
解决问题的最佳方法可能是将调用移入ionViewDidLoad生命周期事件。来自文档:
ionViewDidLoad: Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewDidLoad event is good place to put your setup code for the page.
class MyPage {
ionViewDidLoad() {
// Add your API call here
}
}
您可以在此处详细了解:https://ionicframework.com/docs/v2/api/navigation/NavController/
您可能仍希望为服务添加某种缓存,除非您明确强制刷新,否则将返回缓存值一段时间。