首页 > 解决方案 > 为什么我的 BehaviorSubject 在我更改页面时会丢失值?

问题描述

我已经搜索了与我的问题相对应的以前的帖子,但我没有找到。

我尝试了此处提供的解决方案,但它对我不起作用。

这是我的问题。我在我的网站上使用用户帐户。有不同的帐户(客户,管理员,经理......)。导航栏适用于用户帐户类型(一个用户帐户 = 一个导航栏)。导航栏是从 db 加载的。

用户帐户模型包括一个数组(特定属性)来存储导航信息。

为此,我使用下面介绍的身份验证服务:

@Injectable({providedIn: 'root'})

export class AuthService {

public currentUserSubject$ = new BehaviorSubject<UserAccount>({} as UserAccount);
public currentUser$: Observable<UserAccount>;

constructor( private http: HttpClient) { 
  this.currentUser$ = this.currentUserSubject$.asObservable();
}

public get currentUserValue(): UserAccount {                 
  return this.currentUserSubject$.getValue();
}            

public get currentUserSubjectValue(): UserAccount{
  return this.currentUserSubject$.getValue();
}

getCurrentUserSubject(): BehaviorSubject<UserAccount> {      
  return this.currentUserSubject$;
}

getCurrentUserObs(): Observable<UserAccount> {               
  return this.currentUser$;
}

LogIn(login: string, password : string): Observable<UserAccount>{
  let apiUserAccount: string = environment.apiAddress + 'UserAccount/' + 'Login?' + 'login=' + login + '&' + 'password=' + password;
  return this.http.get<UserAccount>(apiUserAccount);
}

getNavigation(accountTypeId: number) : Observable<Navigation[]> {
  let apiNavigation: string = environment.apiAddress + 'NavigationByUser/' + accountTypeId;
  return this.http.get<Navigation[]>(apiNavigation);
}

logout() {
  const user = {} as UserAccount;        
  this.updateAndEmitCurrentUser(user);   
}

isLogged(): Observable<boolean> {
  return this.currentUserSubject$.pipe(
    map((user: UserAccount) => <boolean>user.isLogged),  
    take(1)
  );
}

updateCurrentUser(user: UserAccount) {
  this.updateAndEmitCurrentUser(user);
}

updateAndEmitCurrentUser(user: UserAccount) {
  localStorage.setItem("currentUser", JSON.stringify(user));      
  this.currentUserSubject$.next(user);  
}
}

我的 Home 组件包含: currentUserSubject$= new BehaviorSubject({} as UserAccount); 在构造函数中我这样做:

constructor(private router: Router,private authService: AuthService) { 
    this.currentUserSubject$ = this.authService.currentUserSubject$;
}

如果用户未登录,我需要在我的主页上加载默认导航栏。因此,我在 ngOnInit 中创建了一个空的用户帐户来存储导航信息。

ngOnInit(): void {
    if(this.authService.getCurrentUserSubject().getValue().isLogged === undefined){
        const user = {} as UserAccount;
        this.authService.currentUserSubject$.next(user);
        this.authService.getNavigation(this.userAccountType.Customer).subscribe((navigation: Navigation[]) =>{
          user.navigation = navigation;
          user.isLogged = false;
        });
        this.authService.currentUserSubject$.next(user);
        console.log('Header => ' + JSON.stringify(user, null, 4));
    }
}

第一次主页上的导航栏没问题,但是如果我通过单击登录页面更改页面,导航栏就会消失。当我尝试在控制台中显示他的内容时,可观察的 currentUserSubject$ 属性为空。currentUserSubject$ 属性也在 Online 页面上声明,如下所示:currentUserSubject$ = new BehaviorSubject({} as UserAccount);

我在登录页面上的提交方法是:

onSubmit() {
    this.authService.LogIn(this.f.login.value, this.f.password.value).subscribe((user: UserAccount) => {
    if(user){
        let userAccountTypeId = user.userAccountTypeId.valueOf();
        let truckId = user.truckId?.valueOf();
        this.authService.getNavigation(userAccountTypeId).subscribe((navigation: Navigation[]) =>{
        user.navigation = navigation;
        user.isLogged = true;
        this.authService.currentUserSubject$.next(user);
        this.router.navigate([`/useraccount/${truckId}`]);
        });
    }
  }); 
}

在 Header 组件中,我还声明了 BehaviorSubject 属性,如下所示:currentUserSubject$ = new BehaviorSubject({} as UserAccount);

有什么我做错了吗?对不起,如果我有点长。

谢谢你的帮助。

标签: angulartypescriptobservable

解决方案


推荐阅读