我的代码中有以下内容:
function store() {
this.products = [
new product("sku001", "Apple", "Tasty stuff", 1.00, "local"),
...
];
这适用于显示所有产品:
<h3>Products</h3>
<b>Display products: {{store.products}}</b>
<div class="row">
<div ng-repeat="product in store.products">
<img ng-src="@Url.Content("~/Content/images/products/{{product.sku}}.png")" alt="{{product.name}}"><p></p>
<p>{{product.description}}</p>
</div>
展示的产品:
现在,我不想对值进行硬编码,而是想从一个 restful api 加载它们:
function store($resource) {
var Resource = $resource('/api/products/');
this.products = Resource.query();
console.log(this.products)
这似乎也可以正常工作,但值的格式略有不同(大写/不同的键名):
[{"SKU":"sku001","Name":"Apple","ProductType":"local","Description":"Tasty stuff","Allowance":1073741824,"Price":1}]
我想使用从 API 收到的数据来创建与我当前格式匹配的对象数组,但我遇到了一些问题:
function store($resource) {
var Resource = $resource('/api/products/');
this.products = Resource.query(function (data) {
var product = {};
var productsList = []
for (i = 0; i < data.length; i++) {
product = {
sku: data[i].SKU,
name: data[i].Name,
description: data[i].Description,
price: data[i].Price,
category: data[i].ProductType
}
productsList.push(product);
}
return productsList;
});
当我运行代码时,会输出:
如您所见,显示的 json 没有被修改,因此没有显示描述/价格。
有谁知道我如何修改使用 $resource 加载的数据然后显示它?
编辑
控制器.js
function storeController($scope, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
}
应用程序.js
var storeApp = angular.module('AngularStore', ['ngRoute', 'ngResource']).
//route stuff
}]);
storeApp.factory("DataService", function ($resource) {
var myStore = new store($resource);
var myCart = new shoppingCart("AngularStore");
// return data object with store and cart
return {
store: myStore,
cart: myCart
};
});