Save, Delete and Get in AngularJS

0

I'm doing a fake "CRUD" in AngularJS and I'm having problems with save, delete, and get functions. Only the query () function worked. Can you help me out, please? I saw that the reason is something related to array, I already changed the save function to consider array, but that did not work. And with the get I can not get the single element I want.

app.js var app = angular.module('app',['ngResource']);

app.controller("lojaCtrl", function($scope, $resource){

    var Produto = $resource("/loja/produtos/", {
        "save:": {method: 'POST', isArray:true}
    }); 

    $scope.produto = {};
    $scope.produtos = [];

    $scope.getProdutoById = function(){
        Produto.get({Id:$scope.codigo}, function(data) { //função get
            $scope.produto = data;              
        });
    }

    $scope.getProdutos = function(){
        Produto.query(function(data) { //função query
            $scope.produtos = data;
        });
    }

    $scope.selectProduct = function(produto)
    {
        $scope.produto = produto;   
    }

    $scope.saveProduto = function(){
        $scope.products = Produto.query();
        new Produto().$save(function(data) {
            $scope.products.push(data);
        });
    }

    $scope.deleteProduto = function(){
        Produto.delete({Id:$scope.codigo}, function(data) { //função get
        });
    }

});

Index.php %pr_e%

    
asked by anonymous 10.11.2014 / 21:34

1 answer

1

The default of the angular service $ resource is REST. Therefore you must specifically state the HTTP methods that you use if you are not using the REST pattern. Default methods of the $ resource descritps in Angular API:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

If you send a DELETE to a method that only accepts POST, it will probably return "method not allowed".
Another important point is to send data in JSON format. Cover your javascript array this way:

var arrJson = JSON.stringfy(meuArray);

The arrJson variable will contain json in the string format. And since you're sending the content-type as application / json it will probably work:)

    
13.11.2014 / 13:19