【问题标题】:AngularFirebase 2 - AngularFireAuth signout not signing the user outAngularFirebase 2 - AngularFireAuth 注销未注销用户
【发布时间】:2018-07-27 12:37:37
【问题描述】:

我正在使用 angular-firebase 创建一个简单的登录,并使用电子邮件密码作为身份验证方法。但是即使在调用 af.auth.signout() 方法之后,用户也不为空,并且在我重新加载页面时仍然登录。

请输入下面的代码sn-p:

constructor(public af: AngularFireAuth,private router: Router) {
         this.af.authState.subscribe(auth => { 
         if (auth != null) {
          this.authenticated = true;
         }
        }
      )
     }

      login() { 
        this.af.auth.signInWithEmailAndPassword("email","password");
        this.authenticated = true;
      }

    logOut() {
      this.af.auth.signOut();
      this.authenticated = false;
    }

所以当我调用 login() 时,用户最初为 null 并已登录。但是当调用 logOut() 方法时,该方法成功执行,但在我的代码中调用构造函数 firebase.user(auth sn-p) 不为空,因此 this.authenticated 仍然为 true,并且用户已登录。

为什么 logOut() 方法 (this.af.auth.signOut()) 不让用户为空并退出?

【问题讨论】:

  • this.authenticated 的默认值是多少。以及您如何确定注销是否成功?
  • this.authenticated 默认为 false,即使在调用 logOut() 方法后,刷新页面时用户仍处于登录状态。另一个问题是使用 auth.SignIn() 方法成功登录用户需要超过 20 秒。
  • logOut() 方法返回一个承诺。执行logOut().then().catch() 以获取任何错误消息,例如:.signOut().catch(err=> console.log(err)

标签: angular firebase-authentication angularfire2


【解决方案1】:

signOut() 返回一个承诺,所以你最好这样写:

logOut() {
  this.fb.auth.signOut()
    .then(() => {
      this.authenticated = false;
    })
    .catch(error => {
      console.log(error);
    });
}

【讨论】:

    【解决方案2】:

    你需要取消订阅 observable 否则会发生内存泄漏

    private sub: any;
       constructor(public af: AngularFireAuth,private router: Router) {
         this.sub =this.af.authState.subscribe(auth => { 
         if (auth != null) {
          this.authenticated = true;
         }
        }
      )
     }
    
    
    logOut() {
      this.af.auth.signOut();
      this.authenticated = false;
    }
    ngOnDestroy() {
      this.sub.unsubscribe();
    }
    

    【讨论】:

    • 您能详细说明一下吗?如果我们退出,内存泄漏会如何发生?什么是“this.sub”???
    • 您正在订阅 observable 并将 observable 存储到 sub 变量中,以便您可以取消订阅并避免内存泄漏
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2019-01-01
    • 2013-09-10
    • 2017-07-06
    • 1970-01-01
    • 2013-09-18
    相关资源
    最近更新 更多