【问题标题】:Angular.js page not updated after Firebase responseFirebase 响应后 Angular.js 页面未更新
【发布时间】:2016-10-18 21:53:28
【问题描述】:
myApp.controller('RegistrationController', ['$scope',
  function($scope) {
    var auth = firebase.database().ref();
    //  console.log("auth::"+auth);

    $scope.login = function() {
      $scope.message = "Welcome " + $scope.user.email;
    }; //login


    $scope.register = function() {    
      console.log($scope.user.email);
      console.log($scope.user.password);
      console.log("jdxnx::" + auth);
      firebase.auth().createUserWithEmailAndPassword($scope.user.email, $scope.user.password).then(function() {
        $scope.message = "Hi" + $scope.user.email + " you have registered"
      }).catch(function(error) {
        $scope.message = error.message;
        console.log($scope.message);
      }); // //createUser
    }; // register
  }
]); // Controller

在上面的代码中,当我单击提交时,我的注册函数运行,然后在 firebase.auth().createUserWithEmailAndPassword 内部运行,但在我得到 firebase.auth().createUserWithEmailAndPassword($scope.user.email,$scope.user.password) 函数的响应之前,我的事件从它出来,然后从注册函数返回到页面,原因是{{message}} 值在 html 页面中保持空白,尽管在后端 firebase.auth().createUserWithEmailAndPassword($scope.user.email,$scope.user.password) 函数处理并获得响应,但事件在处理完成之前返回页面。我希望该函数事件应该等到我得到响应。

请注意,我使用的是 firebase 3.x.x 。

【问题讨论】:

  • 尝试在`$scope.message = "Hi" + $scope.user.email + "you have registered" '旁边添加$scope.$apply();

标签: javascript angularjs firebase firebase-authentication


【解决方案1】:

firebase.auth().createUserWithEmailAndPassword 是一个不属于 Angular.js 的异步函数。因此,Angular.js 无法感知到其对$scope 的回调所做的修改,因此它不会更新页面。回调完成后尝试添加$scope.apply()

firebase.auth().createUserWithEmailAndPassword($scope.user.email, $scope.user.password).then(function() {
    $scope.message = "Hi" + $scope.user.email + " you have registered"
    $scope.apply();
  }).catch(function(error) {
    $scope.message = error.message;
    console.log($scope.message);
    $scope.apply();
  });

您可能感兴趣的其他内容:

  • 看看AngularFire 项目,它将负责在Firebase 操作后触发Angular.js。
  • 不推荐使用带有独立控制器和$scope 的 Angular.js 的方式,并且已经有一段时间没有使用了。您可能想看看 Controller-As 语法 (Angular.js 1.3+) 或更好的组件 (Angular.js 1.5+)。

【讨论】:

  • 感谢 Hugo,它正在工作,并且在代码中正确 $scope.$apply()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
相关资源
最近更新 更多