您的位置:首页 > 其它

关于TypeScript页面跳转,事件监听和数据传递

2017-11-24 15:17 417 查看

ionic3采用的是typescript写法,页面间跳转的几种方式。

页面堆栈方式(NavController)

先进后出,后进先出,push()和pop(),在需要跳转的页面引入 NavController,

NavParams(跳转带过去的参数),在跳转到的页面添加 NavParams 接收传过来

的参数,一般页面跳转都带有返回的按钮,所以和pop()一样,也可以调用

this.navCtrl.pop()返回前一页面。

//跳转页面
import { NavController , NavParams } from 'ionic-angular';
export class HomePage {
constructor(public navCtrl: NavController ,
public navParams : NavParams ) {}

//your codes...
push(){
this.navCtrl.push(xxx,{  //xxx代表跳转到的页面,以及传递的参数
"id" : 1,
"name" : "Neo"
})
}
}

//跳转到的页面
import { NavParams } from 'ionic-angular';
export class xxx {
id : number;
name : string;
constructor(public navParams : NavParams ) {

//your codes...   类似键值对获取数据
this.id = this.navParams.get('id');
this.name = this.navParams.get('name');
}
}


模态化窗口的形式(ModalController)

即一个小弹窗形式,modal跳转也是页面跳转。

和NavController用法是一样的,也可以传递参数到跳转页面,

获取值的方式也是通过NavParams.get();

不同在于设备大小而显示的模态话窗口大小不一样。需要引入ModalController。

import { ModalController } from 'ionic-angular';
export class HomePage {
id : number;
name : string;
constructor(public modal: ModalController ) {

//your codes...
let modal = this.modal.create(xxx,{ //xxx是要跳转到的页面
"id" : 1,
"name" : "Neo"
}) ;
modal.present();
}
}


事件发布订阅(Events)

有时候可能会反复切换和跳转页面,反复修改数据。

但是这时又想让数据同步刷新在页面上,

而且想所有页面都共享所需数据

想只是局部刷新数据,而不是全局刷新,这时就需要用到(Events)事件的发布和订阅了。

参考官方例子 Events

发布页面:

import { Events } from 'ionic-angular';    //导入
...
export class EventsPage {
user : string = 'Events';

constructor(public events: Events) {}

publishEvents(user) {
console.log('User created!')
this.events.publish('user:created',this.user, Date.now());
console.log(this.user)
}
}


要接收数据的页面(订阅页面):

import { Component} from '@angular/core';
import { Events } from 'ionic-angular';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
myEvent : string;
constructor(public events: Events) {
var that = this; //避免作用域混淆
events.subscribe('user:created', (user, time) => {
//HomePage.prototype.myEvent = user;
that.myEvent = user;
});
}
}


Events is a publish-subscribe style event system for sending and responding to application-level events across your app.

注意:

订阅必须在发布之前,不然接收不到。像回调函数,先自己定义方法,当成功执行某件事件后触发。

再通俗易懂点:比如微信公众号,你要先关注才能接收到它的推文,不然它再怎么发推文,你也收不到。也就是说,接收页面必须在发布页面前被加载过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息