typescript 如何根据令牌的存在来显示按钮?Angular

8gsdolmq  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(147)

我需要你的帮助。我有很多方法:loginlogoutisAuthenticated。我试图确保登录时,我将令牌存储在localStorage中,如果我有令牌,则只显示Logout按钮。当我登录系统时,一切正常,但重新加载页面后,我看到剩下的2个按钮,而不是Logout。虽然我在localStorage中有令牌。告诉我我的问题是什么,以及如何为logout配置此逻辑?非常感谢
component.ts

export class AppComponent implements OnInit {

  public isAuthenticated: boolean = false;

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

  ngOnInit(): void {
    this.isAuthenticated = this.authService.isAuthenticated();
    this.authService.isAuthenticatedSubject.subscribe(isAuthenticated=> {
        this.isAuthenticated = isAuthenticated;
    });
  }

  logout(): void {
    this.authService.logout().subscribe(() => {});
  }
}

component.html

<div class="buttons">
    <button *ngIf="!isAuthenticated"> Login </button>
    <button *ngIf="!isAuthenticated"> Signup </button>
    <button (click)="logout()" *ngIf="isAuthenticated"> Logout </button>
</div>

auth.service

export class AuthService {

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

  constructor(private httpClient: HttpClient) {}

  public login(body: LoginModel): Observable<SignupLoginResponseModel> {
    return this.httpClient.post<SignupLoginResponseModel>(`${environment.apiUrl}/auth/login`, body)
      .pipe(
        tap((response) => {
          localStorage.setItem('access_token', response.access_token);
          this.isAuthenticatedSubject.next(true);
        })
    );
  }

  public logout(): Observable<Object> {
    return this.httpClient.post(`${environment.apiUrl}/auth/logout`, {})
      .pipe(
        tap(() => {
          localStorage.removeItem('access_token');
          this.isAuthenticatedSubject.next(false);
        })
    );
  }

  public getToken(): string {
    return localStorage.getItem('access_token')!;
  }

  public isAuthenticated(): boolean {
    const token = this.getToken();
    return !!token;
  }

}
mkshixfv

mkshixfv1#

如果令牌存在,则将isAuthenticatedSubject的值示例化为true,否则为false。

public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(Boolean(getToken()));

相关问题