AngularJS:同时$ http get返回$ .each循环中的错误数据

我正在尝试检索多个ID的数据,如下所示:

(严重简化,但我希望我能说清楚)

控制器:

var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactory.get(dataObject); getData.then(function(result){ console.log(result); } }); 

厂:

 app.factory("DataFactory", ['$http', '$rootScope', function($http, $rootScope){ url = 'http://url/api'; var obj = {}; obj.get = function(object){ return $http({ method: 'GET', params: object, url: url }) .then(function(results){ return results.data; }); }; return obj; } ]); 

后端:

  

如果idList是1整数,则返回的数据与id匹配,例如:

 {id: 39, type: "test", value: "value matching id 39"} 

但是,在idList中应用多个值时,返回的数据不会应用于正确的id:

 {id: 39: type: "test", value: "value matching id 41"} {id: 40: type: "test", value: "value matching id 39"} {id: 41: type: "test", value: "value matching id 40"} 

我希望如果我发回相同的ID,匹配该ID的值将是正确的。 不是这种情况。 有什么办法可以将ID正确绑定到正确的匹配值吗?

编辑:查看chrome中的网络选项卡,会发生以下情况:

1个身份证

 url: api?id=39&type=test result(preview): data: [id: 39, type: test, value: 'value matching id 39'] 

对于3个id

 url: api?id=39&type=test (same for 40 and 41) result(preview): data: [id: 39, type: test, value: 'value matching id 40'] 

它几乎看起来像PHP没有正确处理请求。 打开api url( http:// url / api?id = 39&type = test )总能给我预期的结果。 从javascript多次调用api给了我混淆的结果。

它看起来正确,也许是PHP没有识别“GET”动作。

您是否尝试在工厂中放置console.log以查看是否正在使用正确的URL? (很高兴看到网络)。

你也可以用“糟糕的方式”(只是为了测试),把url硬编码如下:

 url: url + "?id=" + object.id + "&type=" + object.type 

如果在使用弹簧配置和jersey时在java中遇到此问题,则问题可能是由@component标记时资源的单例性质引起的。 当新请求到达时,同一个bean与查询,标题参数和其他业务对象的旧注入值一起使用。 这意味着它将使用旧值获取数据。

修复它的一种方法是在资源类上使用原型范围,以便在每次有请求时获取带有新注入的新实例: @Scope("prototype") 修改get方法签名以便它需要的所有值例如,在方法中注入参数而不是在对象中注入参数。

第二个选项更好,因为实例将被重用,并且每个方法调用只会更改参数。

而不是这个

 @QueryParam("searchTerm") private String searchTerm; @GET private Product findProduct() { productDao.find(searchTerm); } 

做这个

 @GET private Product getProduct(@QueryParam("searchTerm") String searchTerm) { productDao.find(searchTerm); }