[英]How to, in AngularJS, use $http to update persistent memory
这是Angular简介视频系列的代码,该视频系列说明了如何使用持久性存储器中的数据填充角度控制器,但仅说明了如何将新产品评论添加到持久性存储器中。
似乎确实有一些文章解释了如何执行此操作,但是由于我对angular并不陌生,所以恐怕我听不懂其中的任何内容。
我已经弄清楚了使用$ http进行发布请求的语法,但是我看不到如何将代码适合现有结构,因此它将在1)将新元素推送到reviews数组时调用,以及2 )完成后更新视图。
我有兴趣学习一种将新产品评论添加到持久性存储器中的基本方法。
(function() {
var app = angular.module('gemStore', ['store-directives']);
app.controller('StoreController', ['$http', function($http){
var store = this;
store.products = [];
$http.get('/store-products.json').success(function(data){
store.products = data;
});
}]);
app.controller('ReviewController', function() {
this.review = {};
this.addReview = function(product) {
product.reviews.push(this.review);
this.review = {};
};
});
})();
JSON如下所示:
[
{
"name": "Azurite",
"description": "...",
...
"reviews": []
},
...
]
如果store-products.json
只是服务器上的文件,则需要一个实际的后端实现(在PHP,nodejs等中)才能实际更新文件(或更常见的是仅从数据库返回内容)。
通常,您将创建一个save方法,但是不会在每次修改后都发布。 但是,无论哪种情况,取决于您的后端,通常只要单击“保存”按钮,实现就和$http.put('/store-products', store.products)
一样简单。 通常,put可以返回相同的数据,因此通常无需更新视图,因为您只需将其完全设置为您的状态即可。 但是,如果您有可能进行并发编辑,而put则返回修改后的数据,则看起来就像您得到的:
$http.put('/store-products', store.products).success(function(data){
store.products = data;
});
对于添加项目,它可能几乎相同,具体取决于您的数据模型:
$http.post('/store-products', newProduct).success(function(data){
store.products = data;
});
在这种情况下,POST会提供要添加的项目并返回所有产品。 如果有很多产品-也就是说,产品更像是大型数据库,而不是“文档”中的小型数据库,那么该帖子通常会在服务器处理之后返回添加的项目:
$http.post('/store-products', newProduct).success(function(newProductFromServer){
store.products.push(newProductFromServer); //if newProduct wasn't already in the array
//or, store.products[newProductIdx] = newProductFromServer
});
如果您真的想在每次修改时都调用此函数而不是保存按钮,则可以使用手表 :
$scope.$watchCollection(
function() { return store.products; },
function() { /* call the $http.put or post here */ }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.