角度同步http请求

时间:2017-05-04 10:26:11

标签: angularjs asynchronous controller synchronization factory

我有"角度工厂"和"角度控制器"。

当我调用控制器功能时,从工厂功能调用。 但控制器功能不是等待响应。

这是我的代码。

factory Controller

$scope.deleteCountry = function (countryId, countryName, index) {
    alert(countryId + " " + countryName + " " + index);
    apiUrl = url + '/' + version + '/country';        
    $scope.hasDelete = CommonFactory.deleteEntById(apiUrl,countryName,countryId);       

    alert($scope.hasDelete);
    if ($scope.hasDelete == true) {
        $scope.dataList.splice(index, 1);
        ShowMessage('Hata', 'Silme işlemi başarılı', 1);
    }
    else {
        ShowMessage('Hata', 'Silme işlemi başarılı değil', -1);
    }

}

2 个答案:

答案 0 :(得分:0)

我们知道JavaScript's默认行为是Asynchronous,因此无论您的代码执行什么,它都不会等待输出。要解决您的问题,有两种方法可以实现callback模式或实现promise。我建议你实施承诺。 Angular$q服务,通过使用此服务,我们可以解决此问题。所以首先在common.factory中注入$q

在您的common.factory中,我们会进行一些更改,代码将如下所示: -

common.factory('commonFactory',funtion($http,$q){

  //here your some code according to screenshot

  return{

    deleteEntById : function (url,name,id) { var deferred = $q.defer();
         $http.delete(url)
            .then(function (returnData) {
              //Here you will check true false
              if(returnData.status.data==-1)
              // promise is fulfilled
                deferred.resolve(true);

                else
                // promise is fulfilled
                deferred.resolve(false);


                return deferred.promise;
            }).catch(function(e) {
                // the following line rejects the promise 
                deferred.reject(e);

            }) ;
            // promise is returned
        return deferred.promise;

  }
  }
});

在您的控制器中,我们将进行一些更改

CommonFactory.deleteEntById(apiurl,countryName,countryId).then(function(response){

  //do rest all your code which is depended upon deleteEntById .

});

我希望这能解决你的问题。

答案 1 :(得分:0)

我认为CommonFactory.deleteEntById()必须有return $http.delete();

使用.then().catch();

CommonFactory.deleteEntById(apiUrl, countryName, countryId)
    .then(function(response) {
         console.log('delete success response:', response);
         $scope.dataList.splice(index, 1);
         ShowMessage('Hata', 'Silme işlemi başarılı', 1);
    })
    .catch(function(error) {
         console.error('delete error response:', error);
         ShowMessage('Hata', 'Silme işlemi başarılı değil', -1);
    });
相关问题