Get Data Async Before A `page` Gets Rendered
Solution 1:
For anyone crawling Stackoverflow about restricting page access when using Ionic 2, it looks like Ionic's recommended lifecycle event to tap into is ionViewCanEnter
.
From the docs:
ionViewCanEnter Runs before the view can enter. This can be used as a sort of "guard" in authenticated views where you need to check permissions before the view can enter.
http://ionicframework.com/docs/v2/api/navigation/NavController/
Solution 2:
I'm not sure if this is the official way to do it, but I use the Loading
component for situations like this one. You can find more information in Ionic API Docs.
The page .ts
file would look like this:
import {Component} from'@angular/core';
import {Loading, NavController} from'ionic-angular';
@Component({
templateUrl:"page1.html"
})
exportclassPage1 {
// Loading component
loading : any;
// Information to obtain from servercomments: string = '';
constructor(nav: NavController) {
this.nav = nav;
}
onPageWillEnter() {
// Starts the process this.showLoading();
}
privateshowLoading() {
this.loading = Loading.create({
content: "Please wait..."
});
// Show the loading pagethis.nav.present(this.loading);
// Get the Async information this.getAsyncData();
}
privategetAsyncData() {
// this simulates an async method like// this._service.getComments().then((data) => { // this.comments = data);// this.hideLoading();// });setTimeout(() => {
// This would be the part of the code inside the => {...}this.comments = "Data retrieved from server";
// Hide the loading pagethis.hideLoading();
}, 5000);
}
privatehideLoading(){
// Hide the loading componentthis.loading.dismiss();
}
}
The code is very simple so it doesn't need further details, the idea is to define a loading
so we can show it, then try to obtain the information, and as soon as we get that data, we can hide it calling the this.loading.dismiss()
method.
You can find a working plunker here (using beta.9)
Solution 3:
If you only navigate to that page from one location, couldn't you simply load the data before navigating and using the NavParams
to pass the data?
I am using this structure for a Profile page, from a certain index page I click on a user, and then retrieve his profile before visiting his profile. You can show a nice Loading
while this is happening.
let self=this;
this.profileSvc.getProfile(id)
.then(profile => {
self.nav.push(Profile, {profile:profile});
});
Now in the Profile page you can use the NavParams
to initialize your page.
export classProfile{
profile:any;
constructor(private params:NavParams) {
if(params.get('profile')) {
this.profile = params.get('profile');
} else {
this.profile = this.me;
}
}
Post a Comment for "Get Data Async Before A `page` Gets Rendered"