Angular JS链接两个webservices调用

时间:2016-06-20 10:29:30

标签: angularjs promise angular-promise

希望获得正确的语法来执行以下操作:

1) empty object results = {}
2) first webservice call finished = results.webservice1 = data;
3) second webservice call finished = results.webservice2 = data;
4) Complete

我有类似的东西,但语法感觉不对

 function getClaimSummary(filter) {
        let deferred = $q.defer();

        $http.post(configSettings.Api.GetClaimSummary, filter, { withCredentials : true })
            .success(function(data){
                deferred.resolve(data);
            })
            .error(function(error){
                deferred.reject(error);
            });

        return deferred.promise;
    }

    function getPolicySummary(filter) {
        let deferred = $q.defer();

        $http.post(configSettings.Api.GetPolicySummary, filter, { withCredentials : true })
            .success(function(data){
                deferred.resolve(data);
            })
            .error(function(error){
                deferred.reject(error);
            });

        return deferred.promise;
    }

    function calculateAccumulations(filter){
        service.result = {};

        //Get Claims Summary
        getClaimSummary(filter).then(function(data){
            service.result.claims = data;
        }).then(getPolicySummary(filter).then(function(data){
            service.result.policy = data;
            showAccumulations();
        }));
    }

1 个答案:

答案 0 :(得分:2)

$http本身已经返回一个承诺,所以不需要创建自己的承诺,你也可以同时处理这两个承诺,而不是像这样等待彼此:

function getClaimSummary(filter) {
    return $http.post(configSettings.Api.GetClaimSummary, filter, { withCredentials : true });
}

function getPolicySummary(filter) {
    return $http.post(configSettings.Api.GetPolicySummary, filter, { withCredentials : true });
}

function calculateAccumulations(filter){
    service.result = {};

    //Get Claims Summary
    $q.all({
        claims: getClaimSummary(filter),
        policy: getPolicySummary(filter)
    }).then(function (result) {
        service.result = result;
    });
}

你甚至可以像这样保存一些重复的代码:

function fetchData(type, filter) {
    return $http.post(configSettings.Api[type], filter, { withCredentials : true });
}

function calculateAccumulations(filter){
    service.result = {};

    //Get Claims Summary
    $q.all({
        claims: fetchData('GetClaimSummary', filter),
        policy: getPolicySummary('GetPolicySummary', filter)
    }).then(function (result) {
        service.result = result;
    });
}

可以找到有关$q的更多信息here