Angularjs: $resource随着$http调用而改变

Angularjs: $resource chaning with a $http call

本文关键字:调用 http 改变 随着 resource Angularjs      更新时间:2023-09-26

如何比较这些不同调用的结果?url和水果列表存储在不同的json文件中,在我将它们作为承诺发送之前,我会比较它们。他们应该彼此等待,并在一个共同的承诺中实现。

angular.module('myApp', ['ngResource'])
  .controller('MainCtrl', function($scope, $http, $resource) {
    var list = {};
    $http.get('images.json').then(function(response) {
      response.data.objects.forEach(function(images) {
        list[images.id] = images.url;
      });
    });
    $resource('fruits.json').get().$promise.then(function(response) {
      var list = {
        1: 'badUrlExampleForApple',
        2: 'badUrlExampleForOrange',
        3: 'badUrlExampleForPineapple'
      }
      response.objects.forEach(function(product) {
        if (list[product.id]) {
          console.log(product.name + ': ' + list[product.id]);
        }
      });
    });
  });

我知道这有点奇怪,但我必须这样做。

Plunker示例:http://plnkr.co/edit/ICwvYI?p=preview

任何帮助都将非常感激!

您使用$q.all来获得一个承诺,其.then将它们都解开:

var images = $http.get('images.json');
var fruits = $resource('fruits.json').get().$promise;
$q.all([images,fruits]).then(function(results){
    var images = results[0];
    var fruits = results[1];
    // access to both here, you can compare anything you want
});

$q.all指南说:

将多个承诺合并为一个承诺,当所有的输入承诺都被解决时,这个承诺才会被解决。

在其他承诺库中,如Bluebird和ES6承诺,该功能可能是Promise.all,在原来的Q中是Q.all