WalidRoamsmart WalidRoamsmart - 1 month ago 5
reST (reStructuredText) Question

restful angularjs $http get return null

I'm trying AngularJS for the first time. I'm getting as imple user JSON data from a http-get request, but the object is returned null. I tested my service using chrome and I get this result:

[{"id":1,"email":"walid@gmail.com","name":"walid"}]

Below my js file:

var app = angular.module("userApp", []);
app.controller("userController", function($scope, $http) {
$scope.user = null;
$scope.name = null;

$scope.getUser = function() {
$http({
method : 'GET',
url : '/all',
}).success(function(data) {
$scope.user = json.stringify(data);
}).error(function(data) {
alert('Fail: user is '+data);

});
}
});


My HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SIM Card</title>
<link rel="Stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="Stylesheet" type="text/css" href="css/simcard.css">
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="js/simcard2.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
</head>
<body ng-app="userApp" ng-controller="userController">

<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">User Management</div>
<div class="panel-body">
<form action="">
<div class="form-group">
<label>ID</label> <input type="text" ng-model="email">
<button ng-click="getUser()" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info spacer">
<div class="panel-heading">Result</div>
<div class="panel-body">
<div class="form-group">
<label>Name: </label>
<label>{{user.name}}</label>
</div>
</div>
</div>
</div>
</body>
</html>


I can send the whole maven project in case needed. Thank you for your help.

Regards,
Walid

Answer

The problem is in your config of the request: http://plnkr.co/edit/qEkpUAXQQZmO9iUAZ2aX?p=preview

It doesn't know what type of data you expect in response.

Your http request should look like this:

 $http.get("test.json").success(function(data) {
    $scope.user = data[0];
}).error(function(data) {
    alert('Fail: user is 2 '+data);
});

Update:

Just noticed something in yout HTML - you have there a form with action empty. This is the cause of the request being canceled. in angularjs to have a form, it is enought to add to a div ng-form="myForm" and the input can be just simple button, not submit and it is going to work fine.

Comments