角度服务不按预期操纵值

时间:2016-05-31 14:19:48

标签: angularjs angular-services

我有一个角度服务来处理我的承诺,但我不知道如何操作服务中的$ scope值。我明白我所做的事情是错的,但我不明白我需要做些什么才能做对。

在我的服务中:

.service('resolvePromiseService', function(){
    var publicInterface = {
        resolvePromise: resolvePromise
    }

function resolvePromise(promise, resultObject, callBackFunction, spinner){
    spinner ++;
    promise.then(function(result){
        resultObject = result;
        if(callBackFunction){
            callBackFunction();
        }
    });
    promise['catch'(function(error){
        //generic error handling
    });
    promise['finally'(function(){
        spinner--;
    });
}

并在我的控制器中调用服务

var getInfoPromise = dataAccessService.getInfoByLocationId(locationId).$promise;
resolvePromiseService.resolvePromise(getInfoPromise, $scope.locationInfo, $scope.setUpLocation, $scope.loadingSpinner);

在resolvePromise函数中,我看到值按预期进入并按预期更新,但我认为我误解了$ scope的传递方式。我相信我正在使用vanilla javascript对象替换角度对象。

1 个答案:

答案 0 :(得分:1)

最好的选择是传递范围对象或重新思考如何处理承诺。

发生这种情况的原因与修改参考文献有关。

在你的例子中

$scope.loadingSpinner = 5; // ref1 - val 5
function resolvePromise(promise, resultObject, callBackFunction, spinner){
  // when we enter the function both $scope.loadingSpinner and spinner are both 
  // referencing the same variable
  spinner; // ref1 - val5
  // after we increment spinner the local reference is no longer pointing 
  // at the reference
  spinner; // ref2 - val6
  // therefore we are not actually updating the $scope.loadingSpinner 
  //reference just the local spinner one
}

我已经包含了一个代码片段来证明这一点 - 您需要记住,您正在重新分配参考资料,而不是您打算在此实例中执行此操作。

angular
  .module('Test',[])
  .service('IncrementService', incrementService)
  .controller('MyController', myController)

function incrementService() {
  this.increment = function(valToInc) {
    valToInc++;
    console.log(valToInc);
  }
  
  this.incrementScopeField = function($scope, field) {
    $scope[field]++;
    console.log($scope[field]);
  }
}

myController.$inject = ['$scope', 'IncrementService'];

function myController($scope, IncrementService) {
  $scope.number = 5;
  $scope.inc = function() {
    IncrementService.increment($scope.number);
  }
  $scope.inc2 = function() {
    IncrementService.incrementScopeField($scope, 'number');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='Test' ng-controller='MyController'>
  <button ng-click='inc()'>increment value</button><button ng-click='inc2()'>increment scope</button>
  <br/>{{ number }}
</div>