我正在通过 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/
我的用例:
- 我的
服务
中有一个事件列表,我需要为此获取反馈。 EventFeedbackComponent
具有获取单个事件反馈的控件。- 现在,我展示 EventFeedbackComponent 以获取 First Event 的反馈并通过
Subject
监听事件feedbackSubmit
- 在提交
反馈
时,我展示了一个 Success Toast,并在 Service 中切换我的服务变量以显示下一个事件。 - 重复以上几点,直到我获得所有未审查事件的反馈,这些事件具有通过模型显示的相同组件。
最佳答案
选项 1 带参数关闭
Ionic 模态组件让我们有机会用一些参数关闭对话:
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 输入回调
既然我们可以将任何参数传递给模态,那么让我们传递回调函数:
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 上查看
关于angular - ionic 3 : Modal Controller - Get component Instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272171/