ionViewLoaded not being called

2019-09-14 10:13发布

问题:

I'm trying to use the Page Life Cycle Events as seen here. I'm trying to use ionViewDidLoad but it's not firing for me. I created a plunkr to put my example in the most simple terms as possible. I have a log statment inside of ionViewDidLoad, but it's not being fired. If you look at page1.ts and home.ts in the plunkr you'll see the log statements.

The basic code of each file is:

import { NavController } from 'ionic-angular/index';
import { Page1 } from 'page1.ts'
import { Component } from "@angular/core";


@Component({
  templateUrl:"home.html"
})
export class HomePage {

  greeting: string;

  constructor(private nav: NavController) {

    }

    ionViewDidLoad(){
      console.log('home.ts view initialized');
  }

    goToPage1() {
      this.nav.push(Page1);
    }


}

In my own code, i'm making a call to an API and its firing everytime so I need a life cycle hook so that i

回答1:

I think that since your page is a tab, the lifecycle events don't work in the same way they work for regular pages. If you need to do something every time a tab is selected (like obtaining data from a server), then check this part of Ionic docs:

Sometimes you may want to call a method instead of navigating to a new page. You can use the (ionSelect) event to call a method on your class when the tab is selected. Below is an example of presenting a modal from one of the tabs.

<ion-tabs>
  <ion-tab (ionSelect)="getData()"></ion-tab>
</ion-tabs>

And

export class Tabs {
  constructor(...) {

  }

  public getData() {
    // Awesome code doing awesome things...
  }
}

So you can use the (ionSelect)="yourMethod()" to make the call to that API every time the tab is selected.



回答2:

I think to use the Ionic specific lifecycle events you need to use the NavComponent to go push the views.

I replaced the ionViewDidLoad() with ngOnInit() and the console command fired as expected.

http://ionicframework.com/docs/v2/api/navigation/NavController/