![](/img/trans.png)
[英]Why am I getting “Uncaught ReferenceError: userId is not defined” error?
[英]Why am I getting an error, "ReferenceError: categories is not defined" in AngularJS?
在我的理解中, $scope.categories 已經定義好了。 那為什么我會收到此錯誤並且無法訪問 Json 文件中的數據?
這是我的控制器:
(function(){
app.controller('productsCtrl', ['$scope','$cookies', '$http', function($scope,$cookies,$http){
$http.get("controllers/data.json").then(function (response) {
$scope.categories = response.data;
});
$scope.specials = [categories[0].laptops[1], categories[1].accessories[0]];
}]);
})();
這是我的 Json 文件:
[
{
"laptops": [
{
"name": "Asus Laptop",
"price": 300
},
{
"name": "HP Notebook",
"price": 200
}
]
},
{
"accessories": [
{
"name": "WD Hard Drive",
"price": 100
},
{
"name": "WD Blue SSD",
"price": 700
}
]
}
]
您已將響應數據分配到$scope.categories
,您需要使用$scope.categories
而不是categories
並且一旦 http 調用完成,您還應該添加到$scope.specials
(function(){
app.controller('productsCtrl', ['$scope','$cookies', '$http', function($scope,$cookies,$http){
$scope.specials = [];
$http.get("controllers/data.json").then(function (response) {
$scope.categories = response.data;
$scope.specials.push($scope.categories[0].laptops[1]);
$scope.specials.push($scope.categories[1]. accessories[0]);
});
}]);
})();
這里其實有幾個問題。 首先是你從來沒有定義一個名為類別的變量,你有一個名為 $scope 對象的屬性,所以你需要訪問$scope.categories
或直接設置它的response.data
。
其次,你有一個競爭條件問題。 您正在嘗試訪問承諾之外的類別值,這意味着可能在 get 請求返回任何數據之前。 當你像你一樣使用get().then()
,請求之后的代碼不會等待請求完成后再運行,所以先運行速度更快的代碼。 因為正在運行的兩個操作之一是訪問外部端點,另一個是本地 javascript 代碼,所以幾乎可以保證流程是這樣的:
您需要訪問 promise 中的類別,以確保它實際上已在您嘗試訪問它時定義:
$http.get("controllers/data.json").then(function (response) {
$scope.categories = response.data;
$scope.specials = [$scope.categories[0].laptops[1], $scope.categories[1].accessories[0]];
});
像這樣對索引進行硬編碼通常也是一個壞主意,如果數據發生變化,您可能會遇到索引越界錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.