Angular $http 服务未从 .JSON 文件获取对象
Angular $http service not getting objects from .JSON file
这是我的 http 服务代码:
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').then(function(data){
store.products = data;
});
}]);
这是我的 JSON 代码:
[
{
"name": "...",
"price": 20.00,
"description": "...",
"canPurchase": false,
"images": [
"...jpg",
"...jpg",
"...jpg"
],
"reviews": []
},
{
"name": "...",
"price": 15.95,
"description": "...",
"canPurchase": true,
"images": [],
"reviews": []
}
]
当我 运行 本地主机服务器上的代码时,它不显示我的对象。控制台中也没有显示任何错误,所以我看不出哪里出错了。有人能看到这里的问题吗?
您的 json 数据包装在 $http.get
的 response.data
处。
更改为以下代码将解决问题(还要确保您的 json 文件位于正确的位置)。
$http.get('/store-products.json').then(function(res){
store.products = res.data;
});
这是我的 http 服务代码:
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').then(function(data){
store.products = data;
});
}]);
这是我的 JSON 代码:
[
{
"name": "...",
"price": 20.00,
"description": "...",
"canPurchase": false,
"images": [
"...jpg",
"...jpg",
"...jpg"
],
"reviews": []
},
{
"name": "...",
"price": 15.95,
"description": "...",
"canPurchase": true,
"images": [],
"reviews": []
}
]
当我 运行 本地主机服务器上的代码时,它不显示我的对象。控制台中也没有显示任何错误,所以我看不出哪里出错了。有人能看到这里的问题吗?
您的 json 数据包装在 $http.get
的 response.data
处。
更改为以下代码将解决问题(还要确保您的 json 文件位于正确的位置)。
$http.get('/store-products.json').then(function(res){
store.products = res.data;
});