Infinite scroll view persistence


#1

How do I make the returned server data persist or cache when pushing to another view? I use the current infinite scroll information found on the ionic 2 documentation, but I cannot make the initial server request stay within the view or the fetched data from the infinite scrolling. It keeps on reloading the http.get(url). I have done it with other server requests, but can’t seem to get it working with infinite scroll. What should be in the app.ts ?

//Provider.ts

import.....
@Page({....})

constructor(){
}
loadstartData(){
    return new Promise(resolve => {
      this.http.get('someURL.com/json&count=10')
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        });
    });
}
loadData(offset:number) {
    return new Promise(resolve => {
      this.http.get('someURL.com/json&offset='+offset+'&count=5')
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        });
    });
  }
//Page.ts
import(Page, InifiniteScroll) from ...
import(DataServicel) from ...

@Page({...})

export class ListPage {
 public listItems= [];
 public offset = 10;
  constructor(private dataService: DataService) {
  }
ngAfterViewInit() {
    this.getstartData();
  }
getstartData(){
      this.dataService.loadstartData().then(data => {
       for (var i = 0; i < 10; i++) {
        this.listItems.push( this.listItems.length );
      }
    });
}

  doInfinite(infiniteScroll) {
    setTimeout(() => {
      this.dataService.loadData(this.offset).then(data => {
       for (var i = 0; i < 5; i++) {
        this.listItems.push( this.listItems.length );
      }
    });
      infiniteScroll.complete();
      this.offset = this.offset + 5;
    }, 500);
  }

#2

another points --> you do not need to wrap your requests in new Promise …

Observables have a toPromise-function

import 'rxjs/add/operator/toPromise';

return this.http.get(...).map(...).toPromise();

Only a hint :slight_smile:
what do you expect from these lines:

for (var i = 0; i < 10; i++) {
    this.listItems.push( this.listItems.length );
}

You push 10 times the length of you response data on the array


#3

Thank you. I was pulling some of the code from the ionic conference app and the documentation. Do you know if it is necessary to load the service/provider in app.ts and ngAfterViewInit? Will toPromise persist the data? I am having a disconnect on how to properly prevent ionic views , filled with returned json data, from reloading the http request every time I navigate to and from it. It seems like the array refreshes itself.


#4

I was able to solve the issue and figure out the process, using observables and promises. However, virtualscroll does not work within the app and it would be nice to have because a long list takes up memory.