Kuba Chour Kuba Chour - 3 years ago 156
Javascript Question

Refreshing data through constructor in Angular 2 / Ionic 2

I have Ionic 2 app with one view for 3 different data sets. Data are loaded in constructor and based on variable in page params, it's decided which data set to show.

At every successful data call by observable, event handler logs success when data are loaded. But this only works when I click/load view for a first time. If I click for 2nd or any other time, data are not re-loaded (no log). Also, when I just console log anything, it won't show at 2nd+ click.

So I wonder what should I change to load data everytime and how constructor works in this manner.

This is how my code looks like. Jsons are called from namesListProvider.

@Component({
templateUrl: '...',
})
export class ListOfNames {

...
private dataListAll: Array<any> = [];
private dataListFavourites: Array<any> = [];
private dataListDisliked: Array<any> = [];


constructor(private nav: NavController, ...) {

...
this.loadJsons();
console.log('whatever');
}

loadJsons(){
this.namesListProvider.getJsons()
.subscribe(
(data:any) => {
this.dataListFavourites = data[0],
this.dataListDisliked = data[1],
this.dataListAll = data[2]

if (this.actualList === 'mainList') {
this.listOfNames = this.dataListAll;
this.swipeLeftList = this.dataListDisliked;
this.swipeRightList = this.dataListFavourites;
}
else if (...) {
...
}
this.listSearchResults = this.listOfNames;


}, err => console.log('hey, error when loading names list - ' + err),
() => console.info('loading Jsons complete')
)

}

Answer Source

What you're looking for are the Lifecycle events from Ionic2 pages. So instead of using ngOnInit you can use some of the events that Ionic2 exposes:

Page Event        Description
----------        -----------
ionViewLoaded     Runs when the page has loaded. This event only happens once per page being created and added to the DOM. If a page leaves but is cached, then this event will not fire again on a subsequent viewing. The ionViewLoaded event is good place to put your setup code for the page.
ionViewWillEnter  Runs when the page is about to enter and become the active page.
ionViewDidEnter   Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.
ionViewWillLeave  Runs when the page is about to leave and no longer be the active page.
ionViewDidLeave   Runs when the page has finished leaving and is no longer the active page.
ionViewWillUnload Runs when the page is about to be destroyed and have its elements removed. 
ionViewDidUnload  Runs after the page has been destroyed and its elements have been removed.

In your case, you can use the ionViewWillEnter page event like this:

ionViewWillEnter {
  // This will be executed every time the page is shown ...
  this.loadJsons();
  // ...
}

EDIT

If you're going to obtain the data to show in that page asynchronously, since you don't know how long would it take until the data is ready, I'd recommend you to use a loading popup so the user can we aware of something happening in the background (instead of showing a blank page for a few seconds until the data is loaded). You can easily add that behaviour to your code like this:

// Import the LoadingController
import { LoadingController, ...} from 'ionic/angular';

@Component({
  templateUrl: '...',
})
export class ListOfNames {

   ...
    private dataListAll: Array<any> = [];
    private dataListFavourites: Array<any> = [];
    private dataListDisliked: Array<any> = [];

    // Create a property to be able to create it and dismiss it from different methods of the class
    private loading: any;


  constructor(private loadingCtrl: LoadingController, private nav: NavController, ...) {

    ...
    this.loadJsons();
    console.log('whatever');
  }

  ionViewWillEnter {
    // This will be executed every time the page is shown ...

    // Create the loading popup
    this.loading = this.loadingCtrl.create({
      content: 'Loading...'
    });

    // Show the popup
    this.loading.present();

    // Get the data
    this.loadJsons();

    // ...
  }

  loadJsons(){
    this.namesListProvider.getJsons()
    .subscribe(
      (data:any) => {
        this.dataListFavourites = data[0],
        this.dataListDisliked = data[1],
        this.dataListAll = data[2]

         if (this.actualList === 'mainList') {
            this.listOfNames = this.dataListAll;
            this.swipeLeftList = this.dataListDisliked;
            this.swipeRightList = this.dataListFavourites;
         }
         else if (...) {
            ...
         }
         this.listSearchResults = this.listOfNames;

      }, err => console.log('hey, error when loading names list - ' + err),
      () => {

        // Dismiss the popup because data is ready
        this.loading.dismiss();

        console.info('loading Jsons complete')}
    )

  } 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download