我用了events from ionic native . 我有一个登录函数,它将发出一个事件,如果用户成功登录它将触发或发布一个事件,将所有数据传递给作为整个应用程序的根组件的应用程序组件 . 将根据事件传递的数据,该事件是登录者的用户详细信息 . 是的,我可以使用HTML 5 Local Storage执行此操作,但我改为使用Ionic Event . 我只使用html5 localStorage来存储成功登录时从后端响应中获得的Bearer Token .
这是我 login.ts 中的代码
let headers = new HttpHeaders({
Authorization: `Bearer ${result.data.data.token}`,
'Content-Type': 'application/json'
});
console.log(`Header response after authentication: ${headers}`)
this.profileApi.loadDataAfterLogin(headers)
.then(response => {
console.log('Response after successful login', response)
this.events.publish('user:success-login', response.data, Date.now());
})
.catch(error => {
console.log(error)
});
在我的 app.component.ts
我声明了一堆数据的属性 .
username: string = null;
email: string = null;
firstName: string = null;
lastName: string = null;
现在我有一个成功登录时会被解雇的事件吗?因此,app组件将订阅该事件,该事件将根据成功验证后传递的数据设置我的所有属性 .
events.subscribe('user:success-login', (user, time) => {
// user and time are the same arguments passed in `events.publish(user, time)`
console.log('Welcome', user, 'at', time);
this.username = user.username;
this.email = user.email;
this.firstName = user.name.firstName;
this.lastName = user.name.lastName;
});
现在我想将从传递给app.component的登录中的事件获得的所有数据传递给所有其他组件或子组件 .
例如,我有一个 messenger page ,我想将我创建的 app component 中的所有数据传递给 messenger page component 或其他页面或组件?我还希望将其传递给所有其他组件,因为我将使用此数据 .
感谢有人可以提供帮助 . 提前致谢 .