【问题标题】:Angular - Firebase get userdata after redirectAngular - Firebase在重定向后获取用户数据
【发布时间】:2019-04-25 20:35:49
【问题描述】:

我目前尝试使用 signInWithRedirect 重构所有 signInWithPopup 方法,因为它在移动设备上更加用户友好。然而,当我尝试在重定向后检索数据时,我永远无法得到它。我什至尝试设置超时。也许你们中的一些人知道我的问题的解决方案: Firebase doc

我的服务

  public loginWithGoogle(): Promise<firebase.UserCrendential> {
      const provider = new firebase.auth.GoogleAuthProvider();
      return this.angularFireAuth.auth.signInWithRedirect(provider).then(() =>
       this.angularFireAuth.auth.getRedirectResult().then(res => res));
  }

组件

  // binded on a click event on the dom - just wanna log the data not more :(
  public loginWithGoogle(): void {
    this.loginService.loginWithGoogle().then(res => console.log(res))
  }

【问题讨论】:

    标签: angular firebase firebase-authentication angularfire2


    【解决方案1】:

    与 signInWithPopup 不同,signInWithRedirect 调用会导致页面重新加载,并且在此重新加载时不会调用 signInWithRedirect,它的承诺永远不会解决,然后 getRedirectResult() 也不会达到。

    你应该在构造函数上调用 this.angularFireAuth.auth.getRedirectResult() 。当服务从重定向加载时,它提供数据,否则返回{user: null}。一个example on stackblitz

    【讨论】:

      【解决方案2】:

      我以前遇到过这种情况。

      如果您有兴趣,这里有一个解决方法

      您可以在AngularFireAuth 上收听authState Observable。一旦您在组件上的 ngOnInit 订阅它,在重定向之后,authState 将发生变化,并会产生登录用户的详细信息。

      类似这样的:

      import { Component, OnInit } from '@angular/core';
      ...
      import { AngularFireAuth } from 'angularfire2/auth';
      ...
      
      @Component({...})
      export class UserDetailsComponent implements OnInit {
      
        constructor(...public afAuth: AngularFireAuth,...) { }
      
        ngOnInit() {
          this.afAuth.authState.subscribe(user => {
            if(user) {
              console.log('User Details: ', user);
            } else {
              console.log('No user logged in as of now');
            }
          })
        }
      
        ...
      
      }
      

      【讨论】:

      • 它可以工作但完全不满意,如果它不工作为什么还有getRedirectResult()函数?此外,我最初的目标是扩展我的服务方法以在 firestore 中设置用户文档(如果没有的话)。所以我想把这个逻辑全部封装在一个服务中,并尽可能让我的组件保持虚拟......我需要做一个动作 explizit 并且只有在我得到重定向结果之后。
      • 你可以看看在路由器上使用 resolve 函数,就像你在登录时那样,然后你去不同的路线让它做 x angular.io/api/router/Resolve 或者你可以把它封装在你的 auth guard 中异步获取服务中的用户数据
      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2021-04-09
      • 2019-12-30
      • 2018-09-11
      • 2020-11-05
      • 1970-01-01
      相关资源
      最近更新 更多