目的:我想实现在 不同page 之间 的不同子组件 之间的数据交互 但是数据不需要经过父组件
框架:ionic3
准备:
1、新建两个page (page1,page2)
2、新建两个components(c1,c2)
c1组件:显示数据
c1.html
<p>当前值: {{ counter }}</p>
c1.ts
import { Events } from 'ionic-angular';
import { Component, OnChanges, ChangeDetectionStrategy, ChangeDetectorRef, OnInit } from '@angular/core';
@Component({
selector: 'c1',
templateUrl: 'c1 .html',
changeDetection: ChangeDetectionStrategy.OnPush //这里是重点
})
export class C1 {
text:number=0;
constructor(
private cdRef:ChangeDetectorRef // 这个要注意
) {
this.events.subscribe('all', (e) => { // 订阅all对象
console.log(e);
this.text = e.text
this.cdRef.markForCheck(); // 这个要注意
})
}
}
c2:修改数据
c2.html
<button (click)="add()">加1</button>
c2.ts
import { Events } from 'ionic-angular';
import { Component } from '@angular/core';
@Component({
selector: 'c2',
templateUrl: 'c2.html'
})
export class C2 {
text: number;
constructor(public events:Events) {
console.log('Hello TochangeComponent Component');
this.text = 1;
}
add(){
this.text += 1
console.log(this.text);
this.events.publish("all", { text: this.text }) //发布订阅
}
}
page1:用来存放c1,和跳转到page2
page1.html
<c1></c1>
<br>
<button (click)="p()">页面跳转</button>
page1.ts
p(){
this.navCtrl.push('AaPage')
}
page2:用来存c2
page2.html
<c2></c2>
![](https://img.haomeiwen.com/i3832946/e1431317e110b392.png)
![](https://img.haomeiwen.com/i3832946/58c8541db4c713d7.png)
![](https://img.haomeiwen.com/i3832946/1dfaf696413deb7c.png)
总结:其实方法有好多种:input和output经过父组件流过去,本地储存,session... 我这里用的是rxjs,选自己喜欢的吧 W
网友评论