我目前正在嘗試使用$ 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你能用你的控制器代碼更新你的文章嗎? –