javascript - 在 Angular 闭包内引用服务属性/方法的最合适方法是什么?

标签 javascript angularjs

我正在创建一个 Angular 服务,我想知道以下场景的最佳实践是什么。

authModule.service('authService', 
    function($http, $sessionStorage, $window, $q, $rootScope) {

        this.variable1 = true;

        this.processVariable = function () {
            return $http({...}).then(function(response) {
            variable1 = response.data; 
            //line above this will throw an error because it's not scoped

        }, function (reason) {

        });
    }
} 

如果我使用 Knockout,我会添加 var self = this;上面variable1声明然后使用 self.variable1而不是variable1 .

是使用var self = this;最佳实践,或者使用 Angular 时是否有不同的首选方法?

最佳答案

您可以将其定义为变量

 var variable1 = true;

如果要将其设置为实例属性this.variable1 = true;

那么你可以这样做:-

      var _that = this; 
      this.processVariable = function () {
        return $http({...}).then(function(response) {
        _that.variable1 = response.data; 
        //line above this will throw an error because it's not scoped

    }, function (reason) {

    });

原因是当您位于 $http Promise 的回调中时,this 的作用域不会限于您的服务实例。您还可以使用bind更改回调内的上下文以将其范围限定为服务实例。

但是连续进行调用时可能会出现问题(并且因为服务是单例,所以您将修改或覆盖最后返回的调用的 this.variable1 ),而不是确定您到底想做什么,但最好的办法是从服务中的 promise 回调返回数据。

authModule.service('authService', 
    function($http, $sessionStorage, $window, $q, $rootScope) {
      this.processVariable = function () {
        return $http({...}).then(function(response) {
            return response.data; 
            //line above this will throw an error because it's not scoped
        }, function (reason) {
            $q.reject(reason)
        });
    }
} 

关于javascript - 在 Angular 闭包内引用服务属性/方法的最合适方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267920/

相关文章:

javascript - 如何将数组发布到我的 firebase 数据库中?

javascript - 类型错误 : Cannot read property 'focus' of null

javascript - Angularjs 数据更新时闪烁

javascript - 需要帮助以 DRY 格式重写它

javascript - 获取父 <div> 的子 <div> 的值

javascript - AngularJS - 使用循环表值动态添加表行和列

javascript - 父 Controller 上的 $scope.$watch 不会触发子 ng-select

javascript - Angularjs:调用 iframe 中的其他范围

javascript - 使用 forEach 循环遍历另一个数组以获取条件

javascript - DevExpress ChartJS 在点击时显示系列标签