用户在Angular2的Firebase Auth中登录后执行的操作 [英] Action after user login in Firebase Auth in Angular2

查看:104
本文介绍了用户在Angular2的Firebase Auth中登录后执行的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Angular2应用程序中使用Firebase进行用户身份验证。
除了一个例外,它正在完美地工作。用户登录后,我想运行几个方法来检查这是否是用户的第一次登录。我试图把登录变成一个承诺,然而 console.log(this.af.auth)得到null,因为它似乎是在用户点击登录后立即调用的按钮,但在实际登录完成之前。

I'm using Firebase in my Angular2 app for user authentization. It's working perfectly with one exception. After a user logs in I want to run a few methods to check if this is the first login for the user. I tried to turn the login into a promise, however console.log(this.af.auth) yields null as it seems to be called right after the user clicks the log in button but before the actual login is complete.

任何想法如何在用户登录后触发操作?在我的情况下,我想检查用户是否已经在我的数据库中存在,如果没有,创建一个新的用户。

Any ideas how I can trigger an action after the user is logged in? In my case I want to check if the user already exist in my database and if not, create a new user.

 public login() {
    this.af.auth.login()
      .then(() => {
        console.log("user logged in");
        console.log(this.af.auth);
      });
  }


推荐答案

也许这是因为你在回调函数中使用这个关键字,它有自己的变量作用域,它没有 af.auth 属性。

Maybe this is because you are using this keyword in callback function which has its own variable scope and it does not have af.auth property.

试试这个。

Try this.

public login() {
    var me = this;
    this.af.auth.login()
      .then(() => {
        console.log("user logged in");
        console.log(me.af.auth);
      });
}



更新



尝试订阅 auth 对象,并且应该通知auth状态更改。

UPDATE

Try to subscribe on auth object and you should be notified on auth state change.

this.af.auth.subscribe(auth => {
  if(auth) {
    console.log('logged in');
  } else {
    console.log('not logged in');
  }
});

这篇关于用户在Angular2的Firebase Auth中登录后执行的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆