【问题标题】:Accessing $scope from within a .catch function after a promise在 promise 之后从 .catch 函数中访问 $scope
【发布时间】:2018-04-03 22:22:31
【问题描述】:

我遇到了一个无法解决的 $scope 问题。

我的应用程序使用 Google Firebase API 通过发布到 API 来验证用户身份,然后通过更新 $scope 变量向用户显示成功/错误消息。这是我的功能

$scope.message = "";

$scope.signin = function () {

    var auth = firebase.auth();
    auth.signInWithEmailAndPassword(signinEmail, signinPassword).catch(function (error) {
        var errorCode = error.code;
        console.log("errorCode " + errorCode);
        $scope.message = "An error Alert";
});
}

在我的登录函数中更新 $scope 工作正常,但在内部 catch 函数中访问它不起作用。

到目前为止我已经尝试过:

  1. 将我的代码更改为使用“this”而不是 $scope - 这似乎会引起更大的头痛,因为使用“this”时 html 显示错误。 (可能是由于该应用程序使用 ng-Route)我想保留我的应用程序使用 $scope 或 'this'。

  2. 我尝试以各种方式将 $scope 注入到函数中,但均未成功。

  3. 我试图创建第二个函数,可以从我的 catch 块中调用,$scope.updateMessage(){ },但由于它位于 $scope 上,因此不会调用该函数。如果将此用作常规函数var fn = updateMessage(){ },则无法访问范围。

【问题讨论】:

  • 盲猜,尝试将catch函数附加到当前上下文:.catch(...).bind(this)?
  • 您正在更新 Angular 上下文之外的范围变量,需要告诉 Angular 运行摘要。建议您使用angularfire 模块来简化此操作
  • 试试 $scope.$apply(function(){$scope.message = "An error Alert";})

标签: javascript angularjs firebase angularjs-scope firebase-authentication


【解决方案1】:

感谢回复

由于我试图在角度上下文之外更新范围变量,因此我能够通过访问 HTML 元素并使用 $apply 来更改它

var scope = angular.element(document.getElementById('myElement')).scope();
    scope.$apply(function () {
    scope.message = errorMessage;
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-20
    • 2017-11-29
    • 2015-02-20
    • 1970-01-01
    • 2020-07-31
    • 2017-09-09
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多