Pass Nodejs json to Angularjs

Asked

Viewed 404 times

1

I have a server running on Nodejs using Sequelize for ORM, everything works fine, but I needed to pass the query result to the angular. My server is like this:

var express = require('express');
        var bodyParser = require('body-parser');

        var app = express();

        app.use(bodyParser.json());

        app.use(bodyParser.urlencoded({
            extended: true
        }));

        var Sequelize = require('sequelize');

        var sequelize = new Sequelize('nodejs', 'root', '', {
            loggin : console.log,
            define: {
                timestamps : false
            }
        });

        var dataTypes = require('sequelize');

        var user = sequelize.define('usuarios',{
            nome : dataTypes.STRING,
            descricao : dataTypes.STRING
        },{
            instanceMethods : {
                selectAll : function(sucesso, erro){
                    user.findAll({}, {raw : true}).success(sucesso).error(erro);
                },
                selectById : function(user_id, sucesso, erro){
                    user.find({where : {id : user_id}}, {raw : true}).success(sucesso).error(erro);
                },
                add : function(sucesso, erro){
                    var nome = this.nome;
                    var descricao = this.descricao;

                    user.build({nome : nome, descricao : descricao}).save().success(sucesso).error(erro);
                },
                update : function(user_id, sucesso, erro){
                    var id = user_id;
                    var nome = this.nome;
                    var descricao = this.descricao;

                    user.update({nome : nome, descricao : descricao}, {where : {id : id}}).success(sucesso).error(erro);
                },
                remove : function(user_id, sucesso, erro){
                    user.destroy({where : {id : user_id}}).success(sucesso).error(erro);
                }
            }   
        });

        var router = express.Router();

        router.route('/users')
        .get(function(req, res){
            var Usuarios = user.build();
            Usuarios.selectAll(function(data){
                if(data){
                    res.json(data);
                    console.log(data);
                }
                else{
                    res.send(401, 'NADA ENCONSTRADO');
                }
            }, function(error){
                res.send('USUARIO NAO ENCONTRADO');
            });
        });

        app.all('*', function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
            res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
            if ('OPTIONS' == req.method){
                return res.send(200);
            }
            next();
        });
        app.use(router);

        app.listen(8080);
        console.log('rodando na 8080');

and at the angle:

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

    app.controller('GreetingController', ['$scope','$http', function ($scope, $http) {

        $scope.usuarios = [];

        $scope.getPessoa = function(){
            $http.get('http://localhost:8080/users').    
              success(function(data, status, headers, config) {
                if (data.error == 0) {
                    console.log(data);
                  $scope.usuarios  = data; 
                  console.log('getPessoa', $scope.usuarios); 
                };                                           
              }).
              error(function(data, status, headers, config) {
                // log error
            });
        }

        $scope.getPessoa();



    }]);

What is the correct way to obtain this result?

  • Your code is no longer populated with: $Scope.usuarios = date; ??

  • @Can Danielswater explain what his problem is? The JSON is not arriving correctly or $scope.usuarios is not being populated properly? If the problem is in the JSON already confirmed on the server q is being generated correctly?

  • So when I access the url, via browser, the.log console shows me the json

  • I did not understand the problem, but there is a property "dataValues" in sequelize containing the complete structure, it would not be the case to return only an array with the dataValues? http://docs.sequelizejs.com/en/latest/api/instance/

1 answer

1

The angler now uses Promises. So use your code like this.

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

    app.controller('GreetingController', ['$scope','$http', function ($scope, $http) {

        $scope.usuarios = [];

        var getPessoa = function(){
          
            $http.get('http://localhost:8080/users').then(function(retorno) {
            
              $scope.usuarios  = retorno.data; 
              console.log('getPessoa', $scope.usuarios);                          

            }).catch(function(erro) {

              console.error(erro.status);
              console.error(erro.statusText);
            });
        }

        getPessoa();
    }]);

Browser other questions tagged

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