2017-05-04 174 views
1

我有“角度工厂”和“角度控制器”。角度同步http请求

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

这是我的代码。

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); 
    } 

} 
+0

您可以为此执行Promise或回调。根据您的选择,您可以实施。 –

回答

0

我们知道,JavaScript's默认行为是Asynchronous,因此无论你的代码执行,也不会等待输出。要解决您的问题,有两种方法可以执行callback模式或执行promise。我会建议你履行诺言。 Angular$q服务,通过这个我们可以解决这个问题。所以先注入$q common.factory。

在你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 . 

}); 

我希望这将解决您的问题。

+0

$ http本身发送承诺对象 –

+0

这个效果更好。谢谢KP Chundawat; – tuncgulec

+0

我很高兴。这对你有帮助。 –

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); 
    }); 
+0

谢谢你这个奇妙的想法。工作:) – tuncgulec

+0

请接受并upvote,如果有帮助。 –