从 Angular 监控 API 响应

问题描述 投票:0回答:1

我正在尝试监视 api 响应以了解用户当前是否登录。为此,我向 /api/status 发送一个 get 请求以及仅限 http 的 cookie。如果我当前已登录,端点应使用我的用户 ID 进行响应。如果已登录,Angular 不应显示登录/注册链接。 我的代码如下:

export class HeaderComponent implements OnInit {
  authService = inject(AuthService)

  isLoggedIn$ = new BehaviorSubject<Boolean>(false);

  authenticationStatus!: Observable<HttpResponse<object>>;

  constructor() {
    this.authenticationStatus = this.authService.authStatus()

  }
  ngOnInit(): void {
    this.authenticationStatus.subscribe({
      next: (res: any) => {
        if (res.body) {
          const userId = res.body.message;
          console.log("User ID: ", userId);
          this.isLoggedIn$.next(true)
          console.log(this.isLoggedIn$.value);
        } else this.isLoggedIn$.next(false)
      },
      error: (err) => {
        console.log(err)
        this.isLoggedIn$.next(false)
      }
    });
  }
}

authStatus():可观察{ 返回 this.http.get(

${apiUrls.authServiceApi}/status
, { 观察:'响应',withCredentials:true }); }

然后在模板中,我使用:

    <ng-container *ngIf="!isLoggedIn$.value">
      <span
        [routerLink]="['/login']"
        routerLinkActive="router-link-active"
        class="text-xl cursor-pointer text-gray-200 font-bold m-3 hover:underline hover:text-indigo-200"
        >Login</span
      >
      <span
        [routerLink]="['/register']"
        routerLinkActive="router-link-active"
        class="text-xl cursor-pointer text-gray-200 font-bold m-3 hover:underline hover:text-indigo-200"
        >Register</span
      >
</ng-container>

问题是登录/注册链接在登录后不会消失,直到我刷新页面。有什么想法吗?

我期待 isLoggedIn 变量被更新。

angular authentication rxjs frontend reactive-programming
1个回答
0
投票

您可以使用异步管道来订阅可观察对象。

<ng-container *ngIf="!isLoggedIn$ | async">
© www.soinside.com 2019 - 2024. All rights reserved.