简体   繁体   English

处理 BehaviorSubject 更改不起作用

[英]Handling BehaviorSubject changes doesn't work

I've encountered a problem with creating service for authentication and users.我在为身份验证和用户创建服务时遇到了问题。 I've got this component as a header navigation of my app:我将此组件作为我的应用程序的 header 导航:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

import { AuthenticationService } from '@services';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit, OnDestroy {
  sidebarEnabled: boolean = false;
  logged: boolean = false;

  logSubscribtion: any;

  constructor(
    private authService: AuthenticationService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.logSubscribtion = this.authService.getUser().subscribe((logged) => {
      if (logged !== null) return (this.logged = true);
      this.logged = false;
    });
  }

  ngOnDestroy(): void {
    this.logSubscribtion.unsubscribe();
  }

  toggleSidebar(): void {
    this.sidebarEnabled = !this.sidebarEnabled;
    console.log(this.logged);
    console.log(this.authService.isLogged());
  }

  logout(): void {
    this.authService.signOut();
    this.router.navigateByUrl('/auth/login');
  }
}

And here's the code of HTML component that I want to change when logged off:这是我在注销时要更改的 HTML 组件的代码:

<div id="nav-container">
  <div class="wrapper">
    <nav id="main-nav">
      ...
      <ul class="nav-menu">
        <li class="nav-item" *ngIf="logged == false">
          <a
            routerLink="/auth/login"
            routerLinkActive="active"
            title="Sign in"
            class="nav-link"
          >
            Sign in
          </a>
        </li>
        <li class="nav-item" *ngIf="logged == false">
          <a
            routerLink="/auth/register"
            routerLinkActive="active"
            title="Sign up"
            class="nav-button-link"
          >
            Create free account
          </a>
        </li>
        <li class="nav-item" *ngIf="logged">
          <a
            routerLink="/panel/dashboard"
            routerLinkActive="active"
            title="Dashboard"
            class="nav-button-link"
          >
            My account
          </a>
        </li>
        <li class="nav-item" *ngIf="logged">
          <a (click)="logout()" title="Logout" class="nav-link">
            Logout
          </a>
        </li>
      </ul>
      ...
    </nav>
  </div>
</div>

But when I click on logout link, the header still shows me the "My account" and "Logout" links.但是当我点击注销链接时,header 仍然显示“我的帐户”和“注销”链接。

Also, here's the getUser method from auth service:此外,这是来自 auth 服务的 getUser 方法:

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  private user$ = new BehaviorSubject<User | null>(null);

  constructor(private http: HttpClient, private tokenStorage: TokenStorage) {}

  setUser(user: User | null): void {
    if (user) this.user$.next(user);
  }

  getUser(): Observable<User | null> {
    return this.user$.asObservable();
  }

  signOut(): void {
    this.tokenStorage.signOut();
    this.setUser(null);
  }
}

From your signOut method you are calling setUser with null Value.从您的 signOut 方法中,您使用 null 值调用 setUser。 And in setUser you have check if(user), this condition will fail.在 setUser 中你检查了 if(user),这个条件将失败。 Hence it will not call subject.next.因此它不会调用 subject.next。 Change your signout method to:-将您的注销方法更改为:-

  signOut(): void {
    this.tokenStorage.signOut();
    this.user$.next(null);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM