解析两个json数据并将其一起显示

时间:2017-05-07 18:43:17

标签: javascript angularjs json

我试图解析两组给定的json数据,它们是: https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json

现在我希望通过http服务将其显示在表格形式的angularjs视图中。我知道如何显示一个网址提供的数据,但如果有两个给定网址并且数据应该一起显示该怎么办?我已经读过它可以通过$ q来实现,但我无法理解如何使用它。请帮忙。对于一个网址,这是一个解决方案。



this.baseUrl = 'some url';
this.loadAllBlogs = function() {

  $http({
    method: 'GET',
    url: main.baseUrl + '/all'
  }).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(response);
    main.blogs = response.data.data;
    console.log(main.blogs);

  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    alert("some error occurred. Check the console.");
    console.log(response);

  });


}




当有两个网址时该怎么办?

1 个答案:

答案 0 :(得分:0)

使用$q.all()并传入请求承诺的数组。

$q.all().then()中的数据数组与请求数组中的请求的顺序相同

  var urls = ['https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json',
    'https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json'
  ];

  // map array of `$http` promises
  let requests = urls.map((url) => $http.get(url).then((resp) => resp.data));

  $q.all(requests).then((dataArr) => {
      console.log(dataArr);// in same order as urls
  }).catch((err)=>{
      console.log('Something went wrong with requests');
      console.log(err);
  });

DEMO