Margarita
Margarita

Reputation: 277

AngularJS $http REST call returns null data

I have a REST service that returns a JSON object. I am trying to make the authentication but it responses with empty data.

I did notice that the call is asychronous and when the user is pressing the login button it makes the call before getting the username and password. So I decided to use the $q constructor in order to fix it, but the problem consists, it still returns null data.

What am I doing wrong?

Thanks in advance.

factory

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', '$q', function($http, $q) {

    return {
    login: function(username, password) {
        var deferred = $q.defer();

        $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: password})
            .then (function(data, status, headers, config){
                deferred.resolve(data);
            }, function(data, status, headers, config) {
                deferred.reject(data);
            })
        return deferred.promise;
        }   
    }
}])

controller

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = function() {
        User.login($scope.username ,$scope.password)
            .then(function(response) {
                console.log("success!");
                $scope.status = response.status;
                $scope.data = response.data;
                $scope.username = response.username;
                alert("Success!!!    " + JSON.stringify({data: response.data}));
        }, function (response) { 
                $scope.data = response.data || "Request failed";
                $scope.status = response.status;
                console.log("Error!!!");
                alert( "failure message: " + JSON.stringify({data: response.data}));
        })
    };
}])

*****EDIT*****

I did change the code a little bit. I think the problem was how the $http was written.

factory

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', function($http) {
return {
    login: function(username, password) {
return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
        }   
    }
}])

It did somehow worked but it returns loginCheck:false. It seems that it does not recognize the correct username and password.

response = Object {data: Object, status: 200, config: Object, statusText: "OK"}

log:

Object {data: Object, status: 200, config: Object, statusText: "OK"}config: Objectheaders: Objectmethod: 

"POST"paramSerializer: (b)password: "viewer"transformRequest: Array[1]transformResponse: Array[1]url: "http://localhost:8080/CashInRestServices_war/rest/user/login"username: "viewer"__proto__: Objectdata: ObjectloginCheck: false__proto__: 

Objectheaders: (c)arguments: (...)caller: (...)length: 1name: ""prototype: Objectconstructor: (c)__proto__: Object__proto__: ()<function scope>ClosureClosureGlobal: Windowstatus: 200statusText: "OK"__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()

constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()

Upvotes: 2

Views: 14985

Answers (3)

Margarita
Margarita

Reputation: 277

I figured it out. The login function was causing the problem $scope.login = function() so I used the $event object.

html

<div><button ng-click="login($event)" type="submit">Login</button></div>

factory

angular.module('myApp', ['ngRoute'])

.factory('User', ['$http', function($http) {

    return {
        login: function(username, password) {
        // return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
            var data = {username: username,password: password};
            console.log(JSON.stringify(data));
            return $http({
                method:'post', 
                url: 'http://localhost:8080/CashInRestServices_war/rest/user/login',
                data: JSON.stringify(data),
                headers: {'Content-Type': 'application/json'}
            })
        }
    }
}])

controller

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = function(event) {
        event.preventDefault();

        User.login($scope.username ,$scope.password)
            .then(function(response) {
                $scope.status = response.status;
                $scope.data = response.data;
                alert(JSON.stringify({data: response.data}));
        }, function (response) { 
                $scope.data = response.data || "Request failed";
                $scope.status = response.status;
                alert( "failure message: " + JSON.stringify({data: response.data}));
        })
    };
}])

Upvotes: 1

Ivan Coronado
Ivan Coronado

Reputation: 1028

Try like this, anyway if you can show us your console log.

angular.module('myApp', ['ngRoute'])

        .factory('User', ['$http', function($http) {

            return {
                login: function(username, password) {
                    var myUrl = 'http://localhost:8080/CashInRestServices_war/rest/user/login';

                    var data = {
                        username: username,
                        password: password
                    };

                    return $http({
                        url: myUrl,
                        method: 'POST',
                        data: JSON.stringify(data),
                        headers: {
                             'Content-Type': 'application/json'
                        }
                      }).then(function(response) {
                           return response;
                      });
                }   
            }
        }])

Change your controller like this:

.controller('MainCtrl', ['$scope', 'User', function($scope, User) {

    $scope.username = "viewer";
    $scope.password = "viewer";

    $scope.login = login;

    ////////////////////
    function login() {
        User.login($scope.username ,$scope.password)
            .then(function(response) {
                $scope.status = response.status;
                $scope.data = response.data;
                $scope.username = response.data.username; // I dont know if response.data.username exists but i am sure that response.username doesn't
            }
    };
}])

Upvotes: 0

benek
benek

Reputation: 2168

$http service is already returning a promise, so return it directly without using all the plumber :

login: function(username, password) {
       return $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: username});

        }   
    }

Upvotes: 0

Related Questions