Ionic 3:模态控制器 - 获取组件实例

时间:2017-09-18 05:29:49

标签: angular typescript ionic-framework ionic3

我通过ModalController显示组件EventFeedbackComponent。现在,我想订阅Subject中的EventFeedbackComponent。如何访问组件实例,以实现我的目标。

我目前的代码:

let modal   =   this.modalCtrl.create(EventFeedbackComponent);
modal.present();

// This is not working. Throws the error "ERROR TypeError: Cannot read property 'subscribe' of undefined"
modal._component.feedbackSubmit.subscribe(feedbackResponse => {
    console.log(feedbackResponse);
});

文档在这方面没有帮助:https://ionicframework.com/docs/api/components/modal/ModalController/

我的用例:

  • 我的Service中有一个事件列表,我需要获得反馈。
  • EventFeedbackComponent有控制权来获取单个活动的反馈。
  • 现在,我展示EventFeedbackComponent以获取First Event的反馈并通过feedbackSubmit
  • 收听事件Subject
  • 在提交feedback时,我会显示成功Toast并在服务中切换我的服务变量以显示下一个事件。
  • 重复上述观点,直到我获得所有未审核事件的反馈,并通过模型显示相同的组件。

1 个答案:

答案 0 :(得分:19)

选项1使用参数

解除

离子模态组件使我们有机会用一些参数关闭对话:

<强> modal.ts

constructor(public viewCtrl: ViewController) {
  this.prop = params.get('prop');
}

dismiss() {
  this.viewCtrl.dismiss({ test: '1' });
}

在揭幕战中我们应该:

<强> opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.onDidDismiss(data => {
  alert('Closed with data:' + JSON.stringify(data));
});

如果这还不够,那么

选项2通过ViewContainer.emit进行通信

您可以使用ViewController::emit方法将数据发送到开启者

<强> modal.ts

constructor(public viewCtrl: ViewController) {}

sendFeedBack() {
  this.viewCtrl.emit({ someData: '2' });
}

<强> opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.onDidDismiss(data => {
  alert('Closed with data:' + JSON.stringify(data));
});

modal.present().then(result => {
  modal.overlay['subscribe']((z) => {
    alert(JSON.stringify(z));
  })
});

选项3输入回调

由于我们可以将任何参数传递给模态,然后让我们传递回调函数:

<强> opener.ts

let modal = this.modalCtrl.create(TestComponent, { 
  'prop': 'prop1', 
  onFeedBack: (data) => {
    alert('Input callback' + JSON.stringify(data));
  }
});

<强> modal.ts

onFeedBack: Function;

constructor(params: NavParams) {
  this.onFeedBack = params.get('onFeedBack');
}

sentThroughInputCallback() {
  this.onFeedBack({ s: '2' });
}

如果您仍想获得组件实例,那么:

选项4获取组件实例

只有在创建组件实例后才能获取它:

<强> opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.present().then(result => {
  const testComp = modal.overlay['instance'] as TestComponent;
  testComp.feedbackSubmit.subscribe(() => {
    alert(1);
  })
});

Ng-run Example

上查看
相关问题