如何在angularjs中将服务转换为异步服务

时间:2016-12-25 09:19:16

标签: angularjs asynchronous promise

下面的

是调用服务" flightPricerequest"

的功能
$scope.flight.blockNow= function(offer,metaData){
  SearchFlightsServices.flightPricerequest($scope,offer,metaData);
}

这是我的服务:

var flightPricerequest=function($scope,offer,metadata){
    var url = webroot + 'flights/pricerequest';
    $scope.data = {
        "type"              : "json",
        "Search_cretaria"   : $scope.flight.search,
        "selectedOffer"     : offer,
        "Metadata"          : metadata,
        "EchoToken"         : $scope.flight.EchoToken
    };

    $http.post(url, $scope.data).success(function(data, status, headers, config) {
    if(data.Error){
        $scope.flight.error=data.Error;
        $scope.sendErrorMessage($scope.flight.error);
        return false;
    }else{
        if(data == true){
            window.location = webroot+"flights/book";
        }
    }

    }).error(function(data, status, headers, config) {});       
}

我想将此服务转换为异步服务,因此在执行服务时我可以撤消请求,如刷新页面应该立即停止服务所有操作都在服务完成后发生。

1 个答案:

答案 0 :(得分:0)

你可以使用承诺..

var flightPricerequest=function($scope,offer,metadata){
   var def= $q.defer();
    var url = webroot + 'flights/pricerequest';
    $scope.data = {
        "type"              : "json",
        "Search_cretaria"   : $scope.flight.search,
        "selectedOffer"     : offer,
        "Metadata"          : metadata,
        "EchoToken"         : $scope.flight.EchoToken
    };

    $http.post(url, $scope.data).success(function(data, status, headers, config) {
    if(data.Error){
        def.reject();
    }else{
        if(data == true){
             def.resolve();
        }
    }

    }).error(function(data, status, headers, config) {
     def.reject();
    });  

   return def.promise;     
}

现在称为

$scope.flight.blockNow= function(offer,metaData){
         SearchFlightsServices.flightPricerequest($scope,offer,metaData)
.then(function success(){
       window.location = webroot+"flights/book";
      } ,
       function err(){
        $scope.flight.error=data.Error;
        $scope.sendErrorMessage($scope.flight.error);
    });
}

不要忘记将$q作为依赖注入。

您可以阅读有关承诺的更多信息..

  

https://docs.angularjs.org/api/ng/service/ $ Q

     

http://andyshora.com/promises-angularjs-explained-as-cartoon.html