【问题标题】:Ionic 3: Modal Controller - Get component InstanceIonic 3:模态控制器 - 获取组件实例
【发布时间】:2018-02-26 13:41:20
【问题描述】:

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

我当前的代码:

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 以获取第一个事件的反馈并通过 Subject 监听事件 feedbackSubmit
  • 在提交 feedback 时,我会显示 Success Toast 并在 Service 中切换我的服务变量以显示下一个事件。
  • 重复上述点,直到我获得所有未审核事件的反馈,这些事件具有通过模型显示的相同组件。

【问题讨论】:

  • 你能在这里告诉我你的用例吗?
  • 您的设计似乎适得其反。我建议您在服务中使用主题而不是组件
  • 更新了我的用例。猜猜它现在应该更有意义了。

标签: angular typescript ionic-framework ionic3


【解决方案1】:

选项 1 使用参数关闭

Ionic modal 组件让我们有机会用一些参数关闭对话框:

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方法向opener发送数据

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 输入回调

既然我们可以向 modal 传递任何参数,那么让我们传递回调函数:

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

【讨论】:

  • 方法 4 是我所要求的。你有你的+50。非常感谢。
  • 我在 ionic 3.20.0 中测试了方法 4。 "subscribe" 方法不起作用,但你可以用 "on" 方法替换它,它工作正常。谢谢兄弟,我爱你
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 2019-01-17
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多