AngularJS services (update / save)

New to AngularJS and an attempt to understand the structure and try to create a basic CRUD application. I cannot understand what is needed to update an existing record. Here is my service:

angular.module('appServices', ['ngResource']). factory('App', function ($resource) { var Item = $resource('App/:AppId', { //Default parameters AppId: '@id' }, { //Actions query: { method: 'GET', isArray: true }, getById: { method: 'PUT' }, update: { method: 'POST' } }); return Item; }); 

I can run the basic Get all and getById request to fill out the edit form, but where I am stuck. Here is a sample code for getById

  $scope.apps = App.query(); $scope.getEdit = function(AppId) { App.getById({id:AppId}, function(app) { $scope.original = app; $scope.app = new App(app); }); }; $scope.save = function() { //What type of information should go here? //Do I need to make changes to the appServices? }; 

I think I'm just not sure what next with respect to updating existing information or how the application object will be passed to the API, can someone point me in the right direction or show me a quick update method?

+6
source share
2 answers

This is a really dirty way to handle save operations in angular. For one - you should not use PUT operations for receive requests, and secondly - all this is already built into angular. See below.

 var Item = $resource( 'App/Details/:AppId', { AppId: '@id' } ); var item = Item.get({ id: 1 }, function( data ) { data.setAnothervalue = 'fake value'; data.$save(); ); 

What I'm doing here is to get an β€œItem” and then immediately save it with the new data after it is returned.

Angular JS provides a stack of default values, including query, save, delete / delete, get.etc. And for most RESTful APIs, you really don't need to add much, if anything. For more information, see Resource documents, in particular, information on default values: http://docs.angularjs.org/api/ngResource . $ Resource

In addition, as soon as you receive the descriptor, you can use $ save for create / update operations, but using the POST / PUT (RESTful) conventions. If you do, check out my article I wrote about not so long ago: http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/

+6
source

Having done a bit more research and looking at the Daniel link (thanks). I got his job.

Controller Method:

  $scope.save = function() { $scope.app.update(); }; 

Factory Service:

  var Item = $resource('App/Details/:AppId', { //Default parameters AppId: '@id' }, { //Actions query: { method: 'GET', isArray: true }, getById: { method: 'PUT' }, update: { method: 'POST' } }); Item.prototype.update = function (cb) { console.log(this.AppId); return Item.update({ AppId: this.AppId }, angular.extend({}, this, { AppId: undefined }), cb); }; return Item; 
+4
source

Source: https://habr.com/ru/post/923314/


All Articles