Reputation: 6936
I have a code
In login.ts I am doing
this._events.publish('user:created', 'val', Date.now());
In another page I am doing
this._events.subscribe('user:created', (user,time) => {
// user and time are the same arguments passed in `events.publish(user, time)`
console.log('Welcome', user, 'at', time);
});
But nothing happen in _events.subscribe. It is not working, no console.log.
What am I doing wrong.
Upvotes: 0
Views: 3322
Reputation: 61
The other answers are partially right, but if you are going to use the subscribe inside the constructor you have to make sure your publisher is publishing after your second page had subscribed already.
It works when you have subscribers, you could use:
ionViewDidLeave() {
this.events.publish('queue:name', object);
}
Upvotes: 2
Reputation: 147
you can the call the events publish method once you're logged in.
Declare variable in your component.
ex: Some:any
Publish the event in any method you want.
this._events.publish('user:created', this.some="data", Date.now());
Then you can subscribe the events in constructor of another page.
constructor(private events: Events) {
this._events.subscribe('user:created', (user,time) => {
console.log('Welcome', user, 'at', time);
});
}
Upvotes: 0
Reputation: 3838
Sounds like you are trying to communicate between 2 pages? In my experience using Ionic events is not very useful to communicate between 2 pages unless you have an intermediary. If one page fires an event, the other page likely won't be instantiated to hear the event.
Pages can certainly publish events. The subscriptions will likely be more successful in a service/provider or in app.component.ts. Then they can respond to the published events, and navigate to another page or expose properties that were manipulated by events, which the pages can use as needed.
Upvotes: 0
Reputation: 1146
Put your event subscribe code in the constructor of another page.
constructor(private events: Events) {
events.subscribe('user:created', (user,time) => {
// user and time are the same arguments passed in `events.publish(user, time)`
console.log('Welcome', user, 'at', time);
});
}
Upvotes: 2