Your service has to return some promise, observable or invoke a callback. Angular2 is on observables, but I haven’t seen a good example of how to do this particular pattern yet, probably trivial.
As Rxjs observables can act something like promises you need to use .flatMap() or it alias .selectMany() operators, please note i’m new to Rxjs, there could be a better way:
var datafunctions= [serviceA.getData, serviceB.getData, serviceC.getData];
function getNext() {
var func = datafunctions.pop();
func().then(function () {
if (datafunctions.length > 0) getNext();
});
}
getNext();
You’re probably better off with waterfall as this ignores errors.
If you can do the services parallel you could try Promise.all(datafunctions).then(function () { console.log(“all done”); });
@willb i’m almost sure the .then() chaining will get the data in serial way as it should wait for the resolve of the service behind it, the observable i’m no so sure as i just looked to the Rxjs docs to make that code.
I have been using Promises for some time and it has worked like that for me, am i wrong?
Actually only the first get1 is the one that needs to be a promise, the other get# functions would be able to just return a value if they didn’t have an async operation, but as timeout is a function itself you did a good use of the promise here.
Btw can you test the Rxjs approach? i’m not so sure of that one, i just looked to the docs, i’m a noob with Rxjs.
I’ve been struggling to solve this problem in Ionic 2 for the last couple of hours. The suggested approach here would work but seems wrong to me. I would expect the components / routes to be self contained and know what they need to do to resolve their data requirements internally, so you can simply navigate to them using a generic function. Then have something like this in the component:
@CanActivate((to: ComponentInstruction, from: ComponentInstruction) => {
return new Promise((resolve) => {
// Get data asynchronously, then on success set it and resolve...
to.routeData.data['key'] = value;
resolve(true);
});
})
I know this should be NavParams in the context of Ionic 2, just outlining how I would expect it to work. Also NavController does have lifecycle hooks, but this won’t solve the problem of resolving data ahead of view switching in an encapsulated way.
Any progress on this issue?
For me putting data retreival into the calling view seems very wrong, especially if i need the data in main page… @CanActivate didn’t worked for me either. since onPageWillEnter doesn’t say its evaluating promises i don’t think its the correct place for retreival of data…
But after a glimpse into ionics view-controller.js:
ViewController.prototype.willEnter = function () {
ctrlFn(this, 'onPageWillEnter');
};
one can see, that the promise which is returned in the example above is not considered, hence we cant be sure that the data is available prior rendering
But maybe I’m missing some point here