ionic3 左侧菜单栏显示 用户名

网友投稿 636 2022-09-09 10:25:23

ionic3 左侧菜单栏显示 用户名

分析

ionic3导航统一用的是nav导航,可以携带参数,但是左侧菜单栏是在app的根组件中,他的生命周期中,只会加载一次,故,退出登录后,app里面的变量属性不会切换。这里就造成了 用户名无法切换的问题,只显示第一次加载的值

解决办法

参看了下ionic3的官方,可知,有个events的对象,可以发布和订阅消息,这个知识点可以解决我们上面的问题,在app加载的时候 订阅用户的信息。在登录后发布新的用户信息。

具体代码

app.html

{{username}}

{{rolename}}

app.component.ts关键代码

export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HomePage; username: string = this.storage.get("username"); rolename: string = this.storage.get("rolename"); pages: any = []; constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public storage: StorageProvider, private tool: ToolProvider, private alertCtrl: AlertController,public events: Events) { this.initializeApp(); this.pages = [ {index: 1, title: '修改密码', icon: 'icon-password'}, {index: 2, title: '修改个人信息', icon: 'icon-edit'}, {index: 3, title: '版本更新', icon: 'icon-shuaxin'},// {index: 4, title: '系统信息', icon: 'icon-iconfonticonfontjixieqimo' } ]; //接受订阅消息 events.subscribe('user:created', (user, time) => { this.username = user.username; this.rolename = user.rolename; console.log('Welcome', user, 'at', time); }); }

登录页面login.ts的关键代码

= { username: '', password: '', rolename:'' };doLogin() { if (this.userinfo.username == null || this.userinfo.username == "") { this.tools.toast("请输入用户名"); setTimeout(() => { this.nameInput.setFocus(); }, 500); return; } else if (this.userinfo.password == null || this.userinfo.password == "") { this.tools.toast("请输入密码"); setTimeout(() => { this.passInput.setFocus(); }, 500); return; } else { this.{ loginname: this.userinfo.username, password: this.userinfo.password }).subscribe(res => { if (res.success) { console.log(res) this.storage.set("loginname", res.obj.sqpLoginName); this.storage.set("roleid", res.obj.sqpRoleId||0); this.userinfo.rolename = res.obj.sqpRoleName || ""; //发布订阅消息 this.events.publish('user:created', this.userinfo, Date.now()); this.navCtrl.setRoot(HomePage); this.tools.toast('登录成功'); } else { this.tools.toast('用户名或密码错误,请重新输入'); } }, err => { console.error(err); }) } }

自此,大功告成(最喜欢的一句话)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:文件操作如何进制逐行读取(如何按行读取文件)
下一篇:React引入react-transition-group实现过渡效果
相关文章