我的代码就像
login.component.ts
loginSucess () {
this.MenuService.setUserName(userauthresponce.username);
}
MenuService.ts
private usernameSource = new BehaviorSubject<any>(0);
setUserName (username) {
this.usernameSource.next(username);
}
getUserName () {
return this.usernameSource.asObservable();
}
other.component.ts
constructor(MenuService:MenuService) {
this.MenuService.getUserName().subscribe(responce => {
console.log('username', responce);
this.username = responce;
});
}
/* it's not working hear*/
switchrole() {
this.router.navigate(['/dashboard']);
this.MenuService.setUserName(this.username);
}
我在第一次登录时获取用户名,之后用户点击切换角色按钮时调用切换角色功能,在此功能中我必须将页面导航到仪表板,在这种情况下我将用户名设置为0;
即使我从switchrole()设置了用户名,但这不起作用
我没有收到我的错误请帮帮我
答案 0 :(得分:0)
请尽量不要致电this.usernameSource.asObservable()
并返回this.usernameSource
,因为您可以直接订阅BehaviorSubject
,但不能在Observable上调用下一个;
离。
private usernameSource = new BehaviorSubject<any>(0);
setUserName (username) {
this.usernameSource.next(username);
}
getUserName () {
return this.usernameSource;
}