我目前正在尝试使用$ http服务来尝试读取一些JSON文件。我成功地阅读了它们,但出于某种原因出现为object Object
,所以我无法读取这些对象的属性。
我是否在使用GET
请求时错误地读取文件?但这很奇怪,因为当我在数据上使用JSON.stringify()
时,我可以看到应该在那里的所有属性......只是当我正常得到它们时,它们显示为这些未定义的对象。这可能是我初始化变量的方式吗?
这里是我的功能来从JSON文件中的数据:
myMod.service('deployService', function ($http, envService) {
var projectCache = [];
var envCache = [];
var envFilter = "";
function getDeployments() {
if (!projectCache) {
// return;
} else {
$http({
method: 'GET',
url: '/json_files/dashboard.json'
}).then(
function success(response) {
this.projectCache = response.data;
this.envFilter = envService.envFilter;
for (var i = 0; i < response.data.length; i++) {
// var item = JSON.stringify(response.data[i].environmentStatuses);
var item = response.data[i].environmentStatuses;
console.log("THE ITEM IS: " + item);
// this.envCache.push(item);
envCache.push(item);
}
console.log(envCache);
},
function failure(reason) {
console.log("there was a failure in getProject in deployController")
});
}
};
return {
projectCache: projectCache,
envCache: envCache,
getDeployments: getDeployments,
envFilter: envFilter,
clearCaches: clearCaches
};
});
这里是控制器的代码:你需要包括你的服务作为一个依赖
myMod.controller("deployController", ['$scope', '$http', '$location', 'envService', 'deployService', function ($scope, $http, $location, envService, deployService) {
//store the projects in this array
$scope.projects = [];
$scope.editingData = {};
$scope.selectedRow = []; // initialize our variable to null
$scope.setClickedRow = function (index) { //function that sets the value of selectedRow to current index
$scope.selectedRow[i] = $scope.selectedRow[i] != true;
console.log(index);
console.log("row " + $scope.selectedRow[i]);
};
//being used to fetch the name and to get the index
$scope.getProjName = function (index) {
// $scope.envFilter = {
// name: ""
// };
console.log("INSIDE GETPROJNAEM");
envService.clickedEnv(index, $scope.projects);
//console.log($scope.envFilter);
};
$http({
method: 'GET',
url: './json_files/dashboard.json'
}).then(function successCallback(response) {
$scope.projects = response.data;
}, function errorCallback() {
alert("cant find the dashboard json");
});
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ENVIRONMENT CONTROLLER LOGIC~~~~~~~~~~~~~~~~~~~~~~~~~~~
$scope.projEnvironments = [];
$scope.editingData = {};
deployService.getDeployments();
$scope.projEnvironments = deployService.envCache;
$scope.envFilter = deployService.envFilter;
console.log("DEPLOYSERVICE.ENVCACHE: " + deployService.envCache);
// console.log("projenv: " + $scope.projEnvironments);
// console.log("envFilter: " + $scope.envFilter);
$scope.getBranchName = function (environment) {
envService.setBranchName(environment);
console.log("THE ENVBRANCH:" + $scope.envBranch);
};
}]);
您需要从您的Angular控制器调用服务。然后,您将能够阅读像deployService.GetDeployments() –
@RaniRadcliff是的内容。我在我的控制器中调用'deployService.GetDeployments()',但它仍然返回'object Object'。通常,当一个对象返回时,在Chrome开发者工具中有一个下拉菜单,但是这些对象没有那个 – winsticknova
@winsticknova你能用你的控制器代码更新你的文章吗? –