angularjs中$http嵌套$http的优雅写法

$http.get(url).success(function(){
    ...
    $http.get(url).success(function(){
    ...
    })
})

因为里面的$http用到外面返回的值做地址参数,所以嵌套着写,但这样感觉不是很优雅,有没有一种方法解决,最好给示例......跪拜大神支招

阅读 6k
6 个回答

试试这个呢

$http({ method: 'GET', url: '/someUrl' })
  .then(response => {
    return $http({ method: 'GET', url: response.data.url }).catch(errHandle);
  })
  .then(p => {
     console.log(p)
  })
  .catch(errHandle);

function errHandle(err){
  console.dir(err);
}
$http.get(url).success(function(rsp){
    $scope.fun1(rsp)
})

$scope.fun1 = function(rsp) {     
    $http.get(url, rsp).success(function(){
        //...
    })
}

我的写法是根据模块创建service,由一个专门访问后端的RestService来处理$http请求。具体如下

//RestService,将$http方法封装下,这里只列举了get和post,可能还会有put等方法
function get(){
    return $http.get(url);
}
function post(url,data){
    return $http.post(url,data);
}

//各模块service,eg. UserService, 获取user信息和修改user信息
function getUserInfo(){
    return RestService.get('UserInfoAPI');
}

function modifyUserInfo(data){
    return RestService.post('UserInfoAPI',data);
}

//controller,要给当前的user涨工资15%
UserService.getUserInfo()
    .then(function(response){
        return response;
    })
    .then(function(userInfo){
        userInfo.salary = userInfo.salary * 1.15;
        return UserService.modifyUserInfo(userInfo);
    })
    .then(function(result){
        console.log('success->',result);
    })
    .catch(function(error){
        console.log('something gose wrong->',error);
    })

大概就是这个意思,把嵌套变成链式执行就好了。

Promise.resolve()
    .then(() => $http({method: 'GET', url: url}))
    .then(response1 => $http({method: 'GET', url: response1.url})
    .then(response2 => {
        // ...use response2
    });

需要es6的Promise

AngularJS的 $http返回的是Promise对象,所以如果你使用ECMAScript 7或TypeScriprt的话可以使用async/await来处理:

let fn = function() {
    response_1 = await $http.get(url_1);
    response_2 = await $http.get(url_2, response_1);
}

这样是可以保证使用异步的同时使用同步的思路写代码。

angular $q服务

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题