简体   繁体   中英

Keep data from services in ionic2

I want to keep the data from services in ionic2. Now each time data is loading from the API's i dont want to call each time user go to the view.

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. 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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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