Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Edit: I'm getting the error to save: Error: [$resource:badcfg] save

And this error to get: Error: [$resource:badcfg] get

I suppose it happens 'cause get() expects an object, and my reponse for both is an array: "[{"id":"1","name":"Computador"},{"id":"2","name":"Impressora"}]"

The code was updated and I added the index.html

I'm really confused about how to treat the data on get, save and delete. Must I do it on php?


I have some data on MySQL and want to manage it with AngularJS, but my functions to save, delete and get are not working well, the only one that worked was query().

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($scope.inserir).$save(function(data) {
            $scope.products.push(data);
        });
    }

    $scope.deleteProduto = function(){
        Produto.delete({Id:$scope.codigo}, function(data) {
        });
    }

});

produtos/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);

class Produto
{
    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public $id;
    public $name;
}

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

if (isset($_GET['Id']))
{
    $p = $products[($_GET['id']-1)];
    echo json_encode($p);
    exit;
}

if (!isset($_GET['Id']))
{
    echo json_encode($products);
    exit;
}   

/*$data = file_get_contents('http://localhost/loja/');

$objData = json_decode($data);

$sql = "INSERT INTO t_produtos(nome) VALUES('$objData')";*/ 

Index.html

<body ng-controller="lojaCtrl">
    <input type="text" ng-model="codigo" name="codigo"/>        
    <input type="text" ng-model="produto.id" name="id"/>
    <input type="text" ng-model="produto.name" name="name"/>        
    <button ng-click="getProdutoById()">Get Produto</button>
    <hr/>
    <ul>
        <li ng-repeat="produto in produtos" ng-click="selectProduct(produto)">Id: {{produto.id}} - Nome: {{produto.name}}</li>
    </ul>
    <button ng-click="getProdutos()">Get Produtos</button>
    <hr/>
    <input type="text" ng-model="inserir" name="inserir"/>
    <button ng-click="saveProduto()">Save Produto</button>
    <hr/>
    <button ng-click="deleteProduto()">Delete Produto</button>  
</body>
share|improve this question
    
what is the error you get when you do insert for example? –  assaqqaf Nov 11 at 13:25
    
When I try the save, I get the error: "Error: [$resource:badcfg] save" in the console. errors.angularjs.org/1.3.1/$resource/… This is the link it references. –  Victor Melias Nov 11 at 13:41
    
On, your console check the network tab. and try to find the response of request. –  assaqqaf Nov 11 at 13:44
    
that error is because you're receiving a JSON, but you are waiting an array –  rahpuser Nov 11 at 13:49
    
Humm, the responde to localhost/loja/produtos/… is the array [{"id":"1","name":"Computador"},{"id":"2","name":"Impressora"}], not the data. I guess I need to insert the data to the database with the $save, but I can't do this at all. –  Victor Melias Nov 11 at 13:53

1 Answer 1

The error you are getting is because your resource is waiting an object instead of an array..

The resource is wrong, change it to following:

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

Now you are doing a real 'extend' or overriding the default save method of intances ( the default save method waits for an object not an array, that was the error you were getting )

Try it out..

Also new Producto().$save would do a empty post to the server.. is that what you want? if not you need to pass the values to producto instance with:

new Producto($scope.producto).$save(callback)

or

var product = new Producto();
product.name = $scope.producto.name;
//... other properties
product.$save(callback);

Hope this helps..

share|improve this answer
    
It didn't work but thanks. The problem is that I don't know how to POST my data. Not even get() is working, only query() –  Victor Melias Nov 11 at 16:17
    
@VictorMelias thanks for accepting my answer but if this answer still don't fit your needs, you sholdn't accept it.. lets continue to find a real solution to your problem.. –  rahpuser Nov 11 at 16:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.