Ionic version:
[ ] 2.x
[x] 3.x
[ ] 4.x
I'm submitting a ...
[x] bug report
[ ] feature request
As I've created an ionic app, with basic lazy-loading implementation. Suppose for the sake of an example, my app contains 2 lazy-loaded pages, Page1 & Page2
So in the constructor of page1.ts I've published the event named hello, and inside the constructor of page2.ts I've subscribed to the event named hello.
My app starts with Page1.
But after running up the app, I found that my event isn't been subscribed on publishing the event hello directly from the constructor of Page1. Can you please help me out with this, that why my subscribe method (inside Page2 constructor) isn't listening to the published event from Page1.
Sample Code:
page1.ts
constructor(public events: Events) {
this.events.publish('hello', 'some data');
console.log('Published');
}
page2.ts
constructor(public events: Events) {
this.events.subscribe('hello', (data) => {
console.log('subscribed to hello with data', data)
});
}
As soon as my app starts, only Published logs into the console. and nothing happens after that. But according to my understanding of ionic events, the subscribe method of Page2 should also work after publishing of that event. Isn't it? Please help me out with this.
Page2 must subscribe to 'hello' event before page1 publish it.
When you call Events.publish, it lookup in subscriber list and callback immediately.
@longgt I've tried subscribing to the event first and then publishing it later, but it's not working in that case too. Keep in mind that I'm doing all this between lazy-loaded modules/pages. Can you please give me a clear explanation with an example about how to achieve this.
@saumya04 The following below code is an example.
page1.ts
constructor(public events: Events, public navCtrl: NavController) {
//Don't publish here
}
navigateToPage2() {
//Wait until Ionic module loader has done load Page2 then publish event here
this.navCtrl.push('page2').then(() => {
this.events.publish('hello', 'some data');
console.log('Published');
});
}
In Page1, add handler to any button to trigger navigateToPage2
page2.ts
constructor(public events: Events) {
this.events.subscribe('hello', (data) => {
console.log('subscribed to hello with data', data)
});
}
ionViewWillUnload() {
this.events.unsubscribe('hello');
}
hello event before Page 1 publish itThanks for the issue! We have moved the source code and issues for Ionic 3 into a separate repository. I am moving this issue to the repository for Ionic 3. Please track this issue over there.
Thank you for using Ionic!
Issue moved to: https://github.com/ionic-team/ionic-v3/issues/761
Most helpful comment
@saumya04 The following below code is an example.
page1.ts
In Page1, add handler to any button to trigger
navigateToPage2page2.ts
helloevent before Page 1 publish it