Save, Delete and Get in Angularjs

Asked

Viewed 967 times

0

I am making a false "CRUD" in Angularjs and I am having problems in save, delete and get functions. Only query() function worked. Can you help me, please? I saw that the reason is something related to array, I already changed the save function to consider array, but that didn’t work. And with the get I can’t get the one 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

header('Content-Type: application/json');

$banco = "produtos";
$usuario = "root";
$senha = "";
$hostname = "localhost";
$conn = mysql_connect($hostname,$usuario,$senha); mysql_select_db($banco) or die( "Não foi possível conectar ao banco MySQL");      

$sql = "SELECT * FROM t_produtos";
$rs = mysql_query($sql);

while($row = mysql_fetch_array($rs)){
    $products[] = (object)array(
    'id' =>$row['id'], 
    'name' =>$row['nome']
    );
}

$sql = "INSERT INTO t_produtos(nome) VALUES('inserir')";

echo json_encode($products);

1 answer

1


The default for the $Resource angular service is REST. So you should specifically declare the HTTP methods you use if you are not using the REST standard.
Default methods of $Resource descritps na API of Angular:

{ '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 string format. And how you’re sending content-type as application/json will probably work :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.