Angular中同一方法中的多个帖子请求

时间:2017-04-06 19:02:35

标签: javascript angularjs asynchronous synchronous

        $scope.observer_vel_data = function(){ 
        $scope.showOverlay('loadRefPubVel'); 
        $http({
            //First http post request
            method:'POST',
            url:'/api/observer_vel_data', 
            data:$scope.payload_array,
        }).then(function successCallback(response){
            console.log('API Endpoint: vel data success!'); 
            //Second post request is made in the method call below
            $scope.sentiment_var = $scope.observer_send_sentiment();
            $scope.vel_var = response.data.velocity1;
        }, function errorCallback(response){
            // console.log(response); 
            $scope.addAlert({
                type: 'danger',
                msg: 'API call failed' 
            });
        }).finally(function(){
            console.log("hello");
            console.log($scope.sentiment_var);
            //graph is rendered
            $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
            $scope.hideOverlay('loadRefPubVel'); 
        });
    };

所以我试图渲染一个图表,该图表使用来自两个不同且独立的帖子请求的数据。但是,在第二个post请求的数据到达之前调用graph命令。我怎样才能解决这个问题 ?发布帖子请求和呈现图表的命令在发布的代码中作为注释提及。

        $scope.observer_send_sentiment = function (){  
        // $scope.showOverlay('loadRefSentiment');
        var data = { 
            "angularGroups":$scope.groups
        };
        // console.log(data);
        $http({
            method:'POST',
            url:'http://localhost:9612/sentiment_velocity',
            data:data
        }).then(function successCallback(response){
            var data = response.data;
            var json_obj = JSON.parse(data.replace(/\'/g,'"'));
            var sentiments = json_obj["sentiments"];
            // console.log(sentiments);
            $scope.update_sentiment(sentiments); 
            console.log(sentiments);
            return sentiments;
        }, function errorCallback(response){
            var errmsg = response.statusText; 
            console.log(response); 
            $scope.addAlert({
                type: 'danger',
                msg: 'API call failed (sentiment basic)' + errmsg,  
            });
        }).finally(function(){
            // $scope.hideOverlay('loadRefSentiment');
        });
    };

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望finally(...)中的代码仅在第二个请求结束后执行。

要强制执行此操作,您需要链接HTTP请求promises,这意味着您需要从第一个请求的成功处理程序返回第二个HTTP请求的承诺。您的代码应该或多或少看起来像这样:

$scope.observer_vel_data = function(){ 
    $scope.showOverlay('loadRefPubVel'); 
    $http({
        method:'POST',
        url:'/api/observer_vel_data', 
        data:$scope.payload_array,
    }).then(function successCallback(response){
        console.log('API Endpoint: vel data success!');
        $scope.vel_var = response.data.velocity1;
        return $scope.observer_send_sentiment();

    }).catch(function errorCallback(response) {
        //This catch will handle errors from both HTTP requests
        $scope.addAlert({
            type: 'danger',
            msg: 'API call failed' 
        });
    })
    .finally(function(){
        console.log("hello");
        console.log($scope.sentiment_var);
        //graph is rendered
        $scope.update_velocity($scope.vel_var,$scope.sentiment_var);
        $scope.hideOverlay('loadRefPubVel'); 
    });
};

$scope.observer_send_sentiment = function() {
    return $http({...}).then(function(response) {
        //process the response
        ...
        $scope.sentiment_var = parsedResponseData;
    });
};

请注意,无论是否发生错误,都会始终执行finally回调。如果您希望仅在未遇到错误时执行其中某些操作,请添加另一个.then(function() {...})

编辑:既然我们可以看到observer_send_sentiment做了什么,那么您可能有必要坚持使用.then(function successCallback() {...}, function errorCallback() {...})语法,并为每个请求保留单独的错误回调。请记住,如果您添加了另一个then块并且希望义务链中的错误阻止执行更多.then(function() {...})块,则应在return $q.reject(response)两端添加errorCallback q.reject 1}}秒。在.then(function successCallback() {...}, function errorCallback() {...})语法的错误回调中不使用@Value.Immutable public abstract class AdditionalInfo { abstract @Nullable String getCountry(); public String getCountryCanonical() { return getCountry != null ? getCountry : DEFAULT_VALUE; } } 会导致承诺已解决,而非已拒绝