20

每次页面更改时,我都想执行一些代码。

我可以为每个页面添加一个ngOnDestroy方法。看来我可以使用 Ionic 2 页面生命周期钩子(例如ionViewDidUnload)来获得完全相同的效果,但我没有费心去测试它。我宁愿在主应用程序类中添加一个方法。

我看到您可以订阅 Angular 2路由器事件。我如何翻译它以在 Ionic 2 中使用?我import { Router } from '@angular/router;首先遇到了一个错误:

TypeScript error: <path>/node_modules/@angular/router/src/common_router_providers.d.ts(9,55): Error TS2305: Module '"<path>/node_modules/@angular/core/index"' has no exported member 'NgModuleFactoryLoader'.
TypeScript error: <path>/node_modules/@angular/router/src/router.d.ts(14,39): Error TS2305: Module '"<path>/node_modules/@angular/core/index"' has no exported member 'NgModuleFactoryLoader'.
TypeScript error: <path>/node_modules/@angular/router/src/router_module.d.ts(9,10): Error TS2305: Module '"<path>/node_modules/@angular/core/index"' has no exported member 'ModuleWithProviders'.

网络包配置

var path = require('path');


module.exports = {
  entry: [
    path.normalize('es6-shim/es6-shim.min'),
    'reflect-metadata',
    path.normalize('zone.js/dist/zone'),
    path.resolve('app/app.ts')
  ],
  output: {
    path: path.resolve('www/build/js'),
    filename: 'app.bundle.js',
    pathinfo: false // show module paths in the bundle, handy for debugging
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript',
        query: {
          doTypeCheck: true,
          resolveGlobs: false,
          externals: ['typings/browser.d.ts']
        },
        include: path.resolve('app'),
        exclude: /node_modules/
      }
    ],
    noParse: [
      /es6-shim/,
      /reflect-metadata/,
      /zone\.js(\/|\\)dist(\/|\\)zone/
    ]
  },
  resolve: {
    alias: {
      'angular2': path.resolve('node_modules/angular2')
    },
    extensions: ["", ".js", ".ts"]
  }
};

无论如何,如果有办法使用ionic-angular的Navor服务,这对我来说更有意义。NavController有没有办法做到这一点?

4

6 回答 6

11

Ionic2不使用Angular2's Router。他们有自己的实现NavController


我看到您可以订阅 Angular 2 路由器事件。我如何翻译它以在 Ionic 2 中使用?

您可以合并所有NavController Events并订阅它。

allEvents = Observable.merge(
                 this.navController.viewDidLoad, 
                 this.navController.viewWillEnter, 
                 this.navController.viewDidEnter, 
                 this.navController.viewWillLeave, 
                 this.navController.viewDidLeave, 
                 this.navController.viewWillUnload);

allEvents.subscribe((e) => {
    console.log(e);
});
于 2016-10-07T10:28:27.110 回答
11

另一种选择是创建一个超类,您可以在其中使用ionViewDidUnload方法(或任何其他生命周期挂钩),如下所示:

import { Events } from 'ionic-angular';

export class BasePage {

  constructor(public eventsCtrl: Events) { }

  ionViewDidEnter() {
    this.eventsCtrl.publish('page:load');   
  }

  ionViewDidUnload() {
    this.eventsCtrl.publish('page:unload');   
  }
}

然后在每个页面中你只需要extend那个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);

    //...
}

然后,您可以在主app.ts文件中添加这样的方法来响应这些事件:

  private initializeEventHandlers() {

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

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

  }
于 2016-10-11T06:04:24.570 回答
10

从 Ionic 3.6 开始,您可以使用 App 组件来订阅应用程序范围内的页面更改事件,如下所示:https ://ionicframework.com/docs/api/components/app/App/

例如,如果您想使用 GA cordova 插件跟踪 Google Analytics 中的每个视图更改,您可以像这样修改您的 app.component.ts:

constructor(private app: App, private platform: Platform, private ga: GoogleAnalytics, ...) {
  this.platform.ready().then(() => {
    this.ga.startTrackerWithId('UA-XXX').then(() => {
      this.app.viewDidEnter.subscribe((evt) => {
        // evt.instance is the Ionic page component
        this.ga.trackView(evt.instance.title);
      });
    }).catch(e => console.log('Doh', e));
  }
}
于 2017-08-24T22:57:05.997 回答
5

第一件事路由器存在于@angular/router模块中。

对于侦听路由更改事件,您可以将订阅放在路由器changes对象上。

代码

class MyRouteEventClass {
  constructor(private router: Router) {
     router.changes.subscribe((val) => {
       /* Awesome code here */
     }
    )
  }
}
于 2016-10-06T03:11:40.367 回答
5

您可以使用普通的旧 Javascript 放置在 app.component.ts 中。假设您使用 Ionic2-RC0:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from 'ionic-native';

import { YourPage } from '../pages/yourpage/yourpage';

@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  rootPage = YourPage;

  constructor(platform: Platform) {
    platform.ready().then(() => {

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      window.addEventListener('load', () =>{
         console.log('page changed');
      });
    });
  }

每次使用 NavController 更改页面时,都会page changed在控制台中打印出来。

于 2016-10-12T18:44:39.793 回答
2

在 Ionic2+ 中,您可以简单地订阅要执行代码的事件,如下所示:

this.navCtrl.ionViewWillUnload.subscribe(view => {
    console.log(view);
});

您可以订阅所有生命周期事件

于 2017-07-01T12:45:36.603 回答