1

In my Ionic 2 app I'm getting data from the SqlStorage and from a HTTP.get request. When I get the data from the HTTP request my page refreshes as expected using the new data, but when I get the data from the SqlStorage it doesn't refresh and the new data is only shown when I 'pull to refresh'.

PS: I'm using TypeScript.

This is the SqlStorage get:

 oldFeeds() {
  return new Promise((resolve, reject) => {
    this.storage.get('feeds').then(data => {
      resolve(JSON.parse(data));
    });
  });
}

And this is the HTTP get:

feeds() {
  return new Promise((resolve, reject) => {
    this.http.get('http://foo.bar').map(res => res.json()).subscribe(data => {
      resolve(data);
    },
    e => reject(e));
  });
}

These methods are inside a service and the calls to them are exactly the same:

this.feedsService.oldFeeds().then(data => {
  this.feeds = data;
  this.entries = this.feeds[this.activeIndex].entries;
});

this.feedsService.feeds().then(data => {
  this.feeds = data;
  this.entries = this.feeds[this.activeIndex].entries;
});

Any ideas on why this is happening and what could I do to solve it? Thanks!

Lucas Moulin
  • 2,450
  • 3
  • 32
  • 41

1 Answers1

1

update

To nudge Angulars change detection "manually" you can use ApplicationRef

import {ApplicationRef} from 'angular2/core';

constructor(private appRef:ApplicationRef) {}

oldFeeds() {
  return new Promise((resolve, reject) => {
    this.storage.get('feeds').then(data => {
      resolve(JSON.parse(data));
      this.appRef.tick();
    });
  });
}

original

didn't work - see comments

constructor(private zone:NgZone) {}

oldFeeds() {
  return new Promise((resolve, reject) => {
    this.storage.get('feeds').then(data => {
      this.zone.run(() => {
        resolve(JSON.parse(data));
      });
    });
  });
}

Looks like SqlStorage API isn't patched by Angulars zone and the call needs to be brought back into Angulars zone "manually" for change detection to run.

See also Triggering Angular2 change detection manually

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567