AngularJS 显示来自 Firebase 的承诺

AngularJS display a promise from Firebase

我确信这是一个简单的问题,但由于我在 angular 工作了大约 2 周,现在我似乎无法弄清楚。

我有这个带有 firebase 功能的 facebook 登录:

function FBLogin(){
     var provider = new firebase.auth.FacebookAuthProvider();
     firebase.auth().signInWithPopup(provider).then(function(result) {
      // This gives you a Facebook Access Token. You can use it to access 
      the Facebook API.
      var token = result.credential.accessToken;
      // The signed-in user info.
      var user = result.user;
      console.log(user.displayName);
      $scope.user = user.displayName;
      $scope.loggedIn = true;
      // ...
    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // The email of the user's account used.
      var email = error.email;
      // The firebase.auth.AuthCredential type that was used.
      var credential = error.credential;
      console.log(error);
      // ...
    });
 }

$scope.user 应该在返回承诺时向我显示 HTML 中的用户名,对吗?它不会那样做。

HTML:

调用函数的按钮:

<a ui-sref=".dashboard" class="btn btn-primary">
        <img class="logo-image" src='components/images/login-button-png-
18039.png' width="140" height="50" ng-click="vm.FBLogin()" ng-
if="!loggedIn">
    </a>

应显示数据的字段:

<p ng-if="loggedIn">{{ user }} xxx</p>

用户名显示在控制台中,但未显示在 HTML 中。

Firebase 承诺不是 AngularJS promises

firebase API 返回的承诺未与 AngularJS 框架集成。

使用 $q.when 从 firebase 承诺创建 AngularJS 承诺:

function FBLogin(){
     var provider = new firebase.auth.FacebookAuthProvider();
     //USE $q.when
     $q.when(firebase.auth().signInWithPopup(provider))
       .then(function(result) {
          // This gives you a Facebook Access Token.
          // You can use it to access the Facebook API.
          var token = result.credential.accessToken;
          // The signed-in user info.
          var user = result.user;
          console.log(user.displayName);
          $scope.user = user.displayName;
          $scope.loggedIn = true;
          // ...

    }).catch(function(error) {
      // Handle Errors here.
      var errorCode = error.code;
      var errorMessage = error.message;
      // The email of the user's account used.
      var email = error.email;
      // The firebase.auth.AuthCredential type that was used.
      var credential = error.credential;
      console.log(error);
      // ...
    });
 }

AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性 监视等

需要将 firebase 承诺转换为 AngularJS 承诺,以便将事件带入 AngularJS 执行上下文。

$q.when(value)

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

-- AngularJS $q Service API Reference - $q.when