如何使用承诺有两个HTTP请求 [英] How to use promise with two http requests

查看:167
本文介绍了如何使用承诺有两个HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让情侣HTTP请求,一是在另一个,而我有我的改制JSON对象的麻烦。

我有一个工厂函数,首先我试图让所有的球队,每队都有一个ID,然后我得到的所有消息为每个团队的ID相关的,并把这个消息在第一个JSON对象。

但是这不工作!

  .factory('teamsFactory',函数($ HTTP,CacheFactory,LocaleManager,$ Q)
{   teams.Getteams =功能()
    {
        VAR ZIS =这一点;
    VAR承诺= $ HTTP({方法:GET,网址:HTTP://www.myserver/teams});
    promise.then(功能(响应){    对于(VAR I = 0; I< response.data.length;我++){     zis.getTeamsNews(response.data [I] .idTeam)。然后(功能(newsresponse){     response.data [I]。新闻= newsresponse.data;     });
    }
    },警报('错误'));
    返回的承诺;
    }
    teams.getTeamsNews =功能(idTeam)
    {
    VAR承诺= $ HTTP({方法:GET,网址:http://www.myserver.com/news?team=+ idTeam});
    promise.then(NULL,警报('错误'));
    返回的承诺;
    }});


解决方案

我觉得这是更好地推动所有的 $ HTTP 承诺到一个数组,然后用 $ q.all()将它们分组在一起,而不是叫他们每个单独在一个循环中。试试这个:

请注意,我不得不四处移动你的一些功能,并创建虚拟数据等等,所以你将不得不改变它略微以满足您的应用程序。

演示

  VAR应用= angular.module('plunker',[]);app.controller('MainCtrl',函数($范围,teamsFactory){
  $ scope.name ='世界';  teamsFactory.Getteams()
  。然后(功能(数据){
    $ scope.teamsData =数据;
  });});app.factory('teamsFactory',函数($ HTTP,$ Q){  变种队= {};  teams.getFavoriteTeamsNews =功能(teamId){
    return $ HTTP
      获得(news.json')
      。然后(功能(响应){
        的console.log('gtTeamNews响应,响应);
        返回response.data [teamId]
      })
  }  teams.Getteams =功能(){    VAR ZIS =这一点,        httpConfig = {
          方法:GET,
          网址:teams.json
        };    返回$ HTTP(httpConfig)
      。然后(功能(响应){        VAR teamId,承诺,            请求= [];        对于(VAR I = 0; I< response.data.length;我++){          teamId = response.data [I] .idTeam;
          诺= teams.getFavoriteTeamsNews(teamId);          requests.push(承诺);        }        返回$ Q
          。所有(请求)
          。然后(函数(响应){            angular.forEach(响应函数(newsresponse,指数){
              response.data [指数]。新闻= newsresponse;
            });            返回response.data;          });
      })
      .catch(功能(错误){
        的console.log('错误',错误);
      });  }
  返回球队;
  // teams.TeamsNews =功能(idTeam){
  //返回$ HTTP({方法:GET,网址:http://www.myserver.com/news?team=+ idTeam})
  // .catch(函数(){
  //警报('错误')
  //});  //}});

更新

您还可以重新的因素上面趁许链,这使得它在我看来,更清洁的。这应该给相同的输出,但更平,即具有较小的压痕/回调地狱:

DEMO2

  VAR应用= angular.module('plunker',[]);app.controller('MainCtrl',函数($范围,teamsFactory){
  $ scope.name ='世界';  teamsFactory.Getteams()
  。然后(功能(数据){
    $ scope.teamsData =数据;
  });});app.factory('teamsFactory',函数($ HTTP,$ Q){  VAR responseData,      队= {};  teams.getFavoriteTeamsNews =功能(teamId){
    return $ HTTP
      获得(news.json')
      。然后(功能(响应){
        的console.log('gtTeamNews响应,响应);
        返回response.data [teamId]
      })
  }  teams.Getteams =功能(){    VAR ZIS =这一点,        httpConfig = {
          方法:GET,
          网址:teams.json
        };    返回$ HTTP(httpConfig)
      。然后(功能(响应){        VAR teamId,承诺,            请求= [];        responseData = response.data;        对于(VAR I = 0; I< responseData.length;我++){          teamId = responseData [I] .idTeam;
          诺= teams.getFavoriteTeamsNews(teamId);          requests.push(承诺);        }        返回$ q.all(请求);      })
      。然后(函数(响应){        angular.forEach(响应函数(newsresponse,指数){
              responseData [指数]。新闻= newsresponse;
        });        返回responseData;
      })
      .catch(功能(错误){
        的console.log('错误',错误);
      });  }
  返回球队;});

I'm trying to make couple of HTTP requests, one inside another, and I'm having a trouble restructuring my JSON object.

I have a factory function, first of all i'm trying to get all the teams, each team has an Id, and then i'm getting all the news for each team with the id related, and putting that news in the first JSON object.

but this is not working !

.factory('teamsFactory', function ($http,CacheFactory,LocaleManager,$q) 
{

   teams.Getteams= function() 
    {
        var zis=this;
    var promise=$http({method:"GET",url:"http://www.myserver/teams"});
    promise.then(function(response){

    for (var i=0;i<response.data.length;i++) {

     zis.getTeamsNews(response.data[i].idTeam).then(function(newsresponse){

     response.data[i].news=newsresponse.data;

     });
    }


    },alert('error'));
    return promise;         
    }


    teams.getTeamsNews= function(idTeam) 
    {
    var promise=$http({method:"GET",url:"http://www.myserver.com/news?team="+idTeam});
    promise.then(null,alert('error'));
    return promise;         
    }

});

解决方案

I think it's better to push all the $http promises into an array and then use $q.all() to group them together rather than calling them each individually in a loop. Try this:

Note I had to move some of your functions around and create dummy data etc. so you will have to alter it slightly to fit your app.

DEMO

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, teamsFactory) {
  $scope.name = 'World';

  teamsFactory.Getteams()
  .then(function(data){
    $scope.teamsData = data;
  });

});

app.factory('teamsFactory', function ($http, $q){

  var teams = {};

  teams.getFavoriteTeamsNews = function(teamId){
    return $http
      .get('news.json')
      .then(function(response){
        console.log('gtTeamNews response', response);
        return response.data[teamId];
      })
  }

  teams.Getteams = function(){

    var zis = this,

        httpConfig = {
          method  : "GET", 
          url     : "teams.json"
        };

    return $http(httpConfig)
      .then(function(response){

        var teamId, promise,

            requests = [];

        for(var i = 0; i <response.data.length; i++){

          teamId  = response.data[i].idTeam;
          promise = teams.getFavoriteTeamsNews(teamId);

          requests.push(promise);

        }

        return $q
          .all(requests)
          .then(function(responses){

            angular.forEach(responses, function(newsresponse, index){
              response.data[index].news = newsresponse;
            });

            return response.data;

          });


      })
      .catch(function(error){
        console.log('error', error);
      });   

  }


  return teams;


  // teams.TeamsNews= function(idTeam){
  //   return $http({method:"GET",url:"http://www.myserver.com/news?team="+idTeam})
  //           .catch(function(){
  //             alert('error')
  //           });

  // }

});

update

You could also re-factor the above to take advantage of promise chaining which makes it much cleaner in my opinion. This should give the same output but is more 'flat', i.e. has less indentation/callback hell:

DEMO2

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, teamsFactory) {
  $scope.name = 'World';

  teamsFactory.Getteams()
  .then(function(data){
    $scope.teamsData = data;
  });

});

app.factory('teamsFactory', function ($http, $q){

  var responseData,

      teams = {};

  teams.getFavoriteTeamsNews = function(teamId){
    return $http
      .get('news.json')
      .then(function(response){
        console.log('gtTeamNews response', response);
        return response.data[teamId];
      })
  }

  teams.Getteams = function(){

    var zis = this,

        httpConfig = {
          method  : "GET", 
          url     : "teams.json"
        };

    return $http(httpConfig)
      .then(function(response){

        var teamId, promise,

            requests = [];

        responseData = response.data;

        for(var i = 0; i < responseData.length; i++){

          teamId  = responseData[i].idTeam;
          promise = teams.getFavoriteTeamsNews(teamId);

          requests.push(promise);

        }

        return $q.all(requests);

      })
      .then(function(responses){

        angular.forEach(responses, function(newsresponse, index){
              responseData[index].news = newsresponse;
        });

        return responseData;
      })
      .catch(function(error){
        console.log('error', error);
      });   

  }


  return teams;

});

这篇关于如何使用承诺有两个HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆