ionic 2 page change event

前端 未结 6 2507
深忆病人
深忆病人 2021-02-18 20:38

I want to execute some code every time the page changes.

I could add add an ngOnDestroy method to every page. It appears that I could use Ionic 2 page lifec

6条回答
  •  不思量自难忘°
    2021-02-18 21:21

    Another option would be to create a super class where you can use the ionViewDidUnload method (or any other lifecycle hook) like this:

    import { Events } from 'ionic-angular';
    
    export class BasePage {
    
      constructor(public eventsCtrl: Events) { }
    
      ionViewDidEnter() {
        this.eventsCtrl.publish('page:load');   
      }
    
      ionViewDidUnload() {
        this.eventsCtrl.publish('page:unload');   
      }
    }
    

    Then in every page you just need to extend that BasePage

    @Component({
      templateUrl: 'build/pages/my-page/my-page.html',
    })
    export class MyPage extends BasePage {
    
    constructor(private platform: Platform,
                  private nav: NavController, 
                  private menuCtrl: MenuController,
                  ...,
                  eventsCtrl: Events) //notice that this one does not have the private/public keyword 
      {    
    
        // Due to an issue in angular, by now you must send the dependency to the super class
        // https://github.com/angular/angular/issues/5155
        super(eventsCtrl);
    
        //...
    }
    

    And then, you can add a method like this one in the main app.ts file to respond to those events:

      private initializeEventHandlers() {
    
        this.events.subscribe('page:load', () => {
          // your code...
        });
    
        this.events.subscribe('page:unload', () => {
          // your code...
        });
    
      }
    

提交回复
热议问题