所以我正在AngularJS中构建一个应用程序。我从http请求中填充了两个数组,来自JSON文件(这些文件可以随时更新;一个列表非常不变,另一个列表会更频繁地更改)。我提出了一种在服务模块中执行http请求的方法。
angular.module('vrApp')
.service('aircraftLists', function( $http ) {
//gets aircraft list
this.getACList = function( path, callback ) {
$http.get(path).then(callback)
}
});
然后在控制器中我调用该方法两次,对于我拥有的每个JSON文件,在回调中我构建链接,将它们放在一个对象中,并将对象放在一个数组中。
'use strict';
var acObj = {
name: '',
latestUrl: '',
mtmUrl: '',
oaUrl: ''
};
angular.module('vrApp')
.controller('mainCtrl', function( $scope, aircraftLists ){
$scope.currACList = [];
$scope.allACList = [];
aircraftLists.getACList('../data/ac.json', function( resp ) {
var aac = acObj;
//loop through list, put in allACList
for( var j = 0; j < resp.data.length; j++ )
{
aac.name = resp.data[j];
aac.latestUrl = "PDM/" + aac.name + "/currlinkindex.htm";
aac.mtmUrl = "PDM/" + aac.name + "/index.htm";
aac.oaUrl = "OA/" + aac.name + "/index.htm";
$scope.allACList[j] = aac;
console.log( $scope.allACList[j] ); //checking the contents of the object in the array
console.log( aac ); //checking the object variable
//clear data from the object
aac = {
name: '',
latestUrl: '',
mtmUrl: '',
oaUrl: ''
};
}
console.log( $scope.allACList );
});
aircraftLists.getACList('../data/current.json', function( response ) {
var cac = acObj;
//loop through list, put in currACList
for( var i = 0; i < response.data.length; i++ )
{
cac.name = response.data[i];
cac.latestUrl = "PDM/" + cac.name + "/currlinkindex.htm";
cac.mtmUrl = "PDM/" + cac.name + "/index.htm";
cac.oaUrl = "OA/" + cac.name + "/index.htm";
$scope.currACList[i] = cac;
console.log( $scope.currACList[i] ); //checking the contents of the object in the array
console.log( cac ); //checking the object variable
//clear data from the object
cac = {
name: '',
latestUrl: '',
mtmUrl: '',
oaUrl: ''
};
}
console.log( $scope.currACList );
});
});
它的工作原理..除了那个,看着控制台日志验证,我收到一个错误,其中第二个列表中的第一个项也是第一个数组中的第一个项。基本上,给定两个列表[abc,def,ghi]和[jkl,mno,pqr],array1的.name属性为“jkl”而不是“abc”;每个其他对象都应该如何。
我很难过。这可能是什么问题?在对象被填充之后以及将对象添加到数组之后,我甚至将对象记录下来。他们都给了我正确的价值。
答案 0 :(得分:0)
这是因为,您正在创建对同一对象的引用两次。 var aac = acObj用于两个服务调用。因此,当您修改acc对象时,在第二次调用中,您正在修改$ scope.allACList和$ scope.currACList中的值。
我建议你使用干净的复制方法。只需在需要时创建临时对象并推送它。
例如:
aircraftLists.getACList('../data/ac.json', function( resp ) {
//var aac = acObj; This line is not necessary
var temp = {};
//loop through list, put in allACList
for( var j = 0; j < resp.data.length; j++ )
{
temp.name = resp.data[j];
temp.latestUrl = "PDM/" + aac.name + "/currlinkindex.htm";
temp.mtmUrl = "PDM/" + aac.name + "/index.htm";
temp.oaUrl = "OA/" + aac.name + "/index.htm";
$scope.allACList[j] =JSON.parse(JSON.stringify(temp))); \\ use clean-copy
console.log( $scope.allACList[j] ); //checking the contents of the object in the array
//console.log( aac ); //checking the object variable - This is not needed
//clear data from the object - This is not needed
//aac = {
//name: '',
// latestUrl: '',
// mtmUrl: '',
// oaUrl: ''
//};
}