简体   繁体   English

将数据保留在ionic2中

[英]Keep data from services in ionic2

I want to keep the data from services in ionic2. 我想保留来自ionic2服务中的数据。 Now each time data is loading from the API's i dont want to call each time user go to the view. 现在,每次从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());

  }

and my function is : 我的功能是:

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);
    });
  }

It depends on what you want. 这取决于您想要什么。 Now the data is fetched every time the user is opening the view. 现在,每次用户打开视图时都将获取数据。

The best way of solving that would probably be to move the call into the ionViewDidLoad lifecycle event. 解决该问题的最佳方法可能是将调用移至ionViewDidLoad生命周期事件中。 From the docs: 从文档:

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
  }
}

You can read more about it here: https://ionicframework.com/docs/v2/api/navigation/NavController/ 您可以在这里了解更多信息: https : //ionicframework.com/docs/v2/api/navigation/NavController/

You might still want to add some sort of caching to your service that will return the cached values for some time unless you explicitly force a refresh. 您可能仍想向服务中添加某种类型的缓存,这些缓存将在一段时间内返回缓存的值,除非您明确强制刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM