每次页面改变时,我都要执行一些代码.
我可以添加一个ngOnDestroy方法到每个页面.看来我可以使用Ionic 2第lifecycle hooks页(例如ionViewDidUnload)获得完全相同的效果,但是我没有打扰测试,我宁愿在主应用程序类中添加一个方法.
我看到你可以订阅Angular 2 Router events.如何翻译用于Ionic 2?我从“@ angular / router”导入{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'.
webpack配置
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"] } };
如果有一种方法可以使用离子角度的Nav或NavController服务,这将更有意义.有办法吗?
另一个选择是创建一个超类,你可以使用这样的ionViewDidUnload方法(或任何其他生命周期钩子):
原文链接:/angularjs/140555.htmlimport { Events } from 'ionic-angular'; export class BasePage { constructor(public eventsCtrl: Events) { } ionViewDidEnter() { this.eventsCtrl.publish('page:load'); } ionViewDidUnload() { this.eventsCtrl.publish('page:unload'); } }
然后在每一页你只需要扩展该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); //... }
然后,您可以在主应用程序文件中添加像这样的方法来响应这些事件:
private initializeEventHandlers() { this.events.subscribe('page:load',() => { // your code... }); this.events.subscribe('page:unload',() => { // your code... }); }