为什么这个 Angular 应用程序无法处理用户状态(登录\退出),从而在用户登录后更改显示内容?

2024-03-11

我正在使用 AngularUI(Angular 包,这个:https://www.npmjs.com/package/firebaseui-angular https://www.npmjs.com/package/firebaseui-angular) 处理 Firebase 上的用户注册\登录

我的应用程序也使用环形火2我在尝试处理用户状态时遇到以下问题(如果用户已登录或注销)。

这是我的家庭组件 TypeScript 代码:

import { Component, NgZone, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  public loggedIn: boolean = false;

  constructor(public afAuth: AngularFireAuth,
              private router:Router,
              private ngZone: NgZone
             ) { }

  ngOnInit(): void {

    this.afAuth.authState.subscribe(this.firebaseAuthChangeListener);

    
  }
   
  private firebaseAuthChangeListener(response) {
    if (response) {
      this.loggedIn = true;
      console.log('Logged in :) ', this.loggedIn);
    } else {
      this.loggedIn = false;
      console.log('Logged out :( ', this.loggedIn);
    }
  }
}

正如你在这个组件中看到的,我声明了布尔值loggedIn变量最初设置为 false,当用户执行登录时我设置为 true(当用户执行注销时再次设置为 false)。我正在尝试使用此变量在该组件的视图中显示不同的内容。

这是该组件的 HTML:

<div *ngIf="loggedIn">
    <h1>Logged in</h1>
    <p>TETS</p>
</div>
<div *ngIf="!loggedIn"> 
    <h1>LOGGED OUT</h1>
    <firebase-ui></firebase-ui>
    <p>BLA</p>
</div>

正如你所看到的,我放置了两个 ngIf 来检查用户是否登录或注销。如果用户注销,则会显示 Firebase UI 界面以允许执行登录。

在这里我得到了一个奇怪的行为。登录 Chrome 控制台后,我有以下输出:

Logged in :)  true

这意味着我正确执行了登录并且loggedIn变量现在为真。

问题是在我的页面中我仍然看到登出输出而不是预期登录。因此该变量的值发生了更改,但基于该值的页面内容loggedIn变量不变。

怎么了?我缺少什么?我该如何解决这个问题?


JavaScript 具有函数作用域,因此使用回调将使context (this) lost, 但是,您必须绑定当前上下文或使用箭头函数从外部词法环境正常调用该方法

绑定当前上下文到稍后要执行的函数:

ngOnInit(): void {
    this.afAuth.authState.subscribe(this.firebaseAuthChangeListener.bind(this));
}

使用箭头函数:

ngOnInit(): void {
    this.afAuth.authState.subscribe(() => this.firebaseAuthChangeListener());
}

Ref https://javascript.info/bind

Ref https://stackoverflow.com/questions/30486345/losing-this-context-in-javascript-when-passing-around-members

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么这个 Angular 应用程序无法处理用户状态(登录\退出),从而在用户登录后更改显示内容? 的相关文章

随机推荐