【问题标题】:How to convert a service to async service in angularjs如何在angularjs中将服务转换为异步服务
【发布时间】:2016-12-25 09:19:15
【问题描述】:

下面是调用服务“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) {});       
}

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

【问题讨论】:

    标签: angularjs asynchronous promise


    【解决方案1】:

    你可以使用承诺..

    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

    【讨论】:

    • 如果我在执行 http 时单击其他链接,它仍然无法正常工作
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2019-09-21
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多