gpt4 book ai didi

javascript - 修改 ngResource 结果时出现问题

转载 作者:行者123 更新时间:2023-12-02 16:37:41 24 4
gpt4 key购买 nike

我的代码中有以下内容:

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>

展示的产品:

display_products

现在,我想从 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;

});

当我运行代码时,会输出以下内容:

updated image

如您所见,显示的 json 尚未修改,因此未显示描述/价格。

有人知道如何修改使用 $resource 加载的数据然后显示它吗?

编辑

Controller .js

function storeController($scope, $routeParams, DataService) {
// get store and cart from service
$scope.store = DataService.store;
$scope.cart = DataService.cart;
}

app.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
};
});

最佳答案

从 Angular 1.2 开始,资源支持 promise 。但他们并没有改变其余的行为。

要利用 $resource 的 Promise,您需要在返回值上使用 $promise 属性。

function store($resource) {
var Resource = $resource('/api/products/');

Resource.query().$promise.then(
//success callback
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);
}
this.products = productsList;

},
//error call back
function(){
});
}

谢谢

关于javascript - 修改 ngResource 结果时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27785258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com