首页 > 解决方案 > 由于 localStorage 变量的值而动态更改导航栏的问题

问题描述

我一直在 Angular 8 中实现一个项目。在这个项目中,需要有一个包含不同导航栏的管理面板。要进入管理面板,您必须登录。登录后,Navbar应将其动态更改为管理导航栏-更改应基于登录结果中的布尔值。为此,我尝试使用BehaviorSubject,但由于某些原因,始终可见 false 值。看起来好像BehaviorSubject没有更新默认值 false

服务:

public isResults: BehaviorSubject<boolean> = new   
BehaviorSubject<boolean>(false);

public _isResults$: Observable<boolean> =    
this.isResults.asObservable();

服务中的登录部分:

yes:boolean = true;
no:boolean = false;

login(user:User){
 if (user.username != null && this.password != null) {
 localStorage.setItem('currentStatus',   
  JSON.stringify(this.yes));

  this.currentStatus =  
  JSON.parse(localStorage.getItem('currentStatus'));

this.isResults.next(this.currentStatus); // updating the BehaviorSubject.
                   // BehaviorSubject should be updated with the boolean value taken from 
                   // the localStorage (in the localStorage the value is as it should be 
                   // but the BehaviorSubject isn't updated, when the value from
                   // localStorge is assigned to it)

应用组件。在 AppComponent 我尝试订阅以BehaviorSubject检查值:

this.employeeService._isResults$.subscribe(
    value => {
       console.log(value);
    }
  )

valuefalse;_

我可以请你帮忙吗?谢谢,

标签: angular

解决方案


推荐阅读