如何使用angularjs在控制器中同步调用

时间:2014-04-08 13:40:48

标签: angularjs synchronous

services.js:

mPortalServices.factory('ChannelTypeService', ['$filter', '$http', '$q', function (filter, $http, $q) {
    var ChannelTypeService = {};
    ChannelTypeService.getAll = function () {
        var defered = $q.defer();
        $http.get('jsondata/ChannelType.json').then(function(response){
          defered.resolve(response.data);
        });
        return defered.promise;
    }
    ChannelTypeService.getSingle2 = function (typeId) {
        var defered = $q.defer();
        ChannelTypeService.getAll().then(function(items){
            var filtered = filter('filter')(items, {
                'TypeId': typeId
            });
            defered.resolve(filtered);
        });
        return defered.promise;
    }

    return ChannelTypeService;
}]);

controllers.js:

//some code here...
var firstChannel = channels[0];

ChannelTypeService.getSingle2(firstChannel.ChannelType).then(
    function(activities) {
        $scope.channelType = activities;
        console.log('1111');
        console.log($scope.channelType);
    } , 
    function(reason) {  }
);
console.log("2222");
console.log($scope.channelType);
if ($scope.channelType.Type == 1 ) {
    $location.path("/list1/");
}
else {
    $location.path("/list2/");
}
return;

我想等待getSingle2函数的结果,但上面的代码是异步的,如何解决问题?

1 个答案:

答案 0 :(得分:0)

将controllers.js更改为以下内容:

function someFunction() {
  //some code here...
  var deferred = $q.defer();

  var firstChannel = channels[0];

  ChannelTypeService.getSingle2(firstChannel.ChannelType).then(
      function(activities) {
          $scope.channelType = activities;
          console.log('1111');
          console.log($scope.channelType);

          console.log("2222");
          console.log($scope.channelType);

          // the following code will now work:
          deferred.resolve();
          if ($scope.channelType.Type == 1 ) {
              $location.path("/list1/");
          }
          else {
              $location.path("/list2/");
          }

      } , 
      function(reason) {  }
  );

  return deferred.promise;
}

任何需要上述功能结果的代码都必须:

someFunction.then(function() {
   // guaranteed to run after, for example, $scope.channelType has been set
})
像Net205一样说,如果你想强制getSingle2同步,你通常不能这样做。