Angularjs $ http.get not working
My goal is to use a REST web service in AngularJS and I am doing some testing right now. Below code fails and throws the following exception. Can you help me identify the problem?
Thanks in advance.
function getUsersFromLocal($scope,$http)
{
$http.get('http://localhost:8080/people').
success(function(data) {
$scope.data = data;
});
return data;
}
Error: TypeError: Cannot read property 'get' of undefined in getUsersFromLocal.
The service is available and I tested it through some REST clients.
If I understood correctly the getUsersFromLocal
function inside the controller, basically the function parameters kill the existence of the object $scope
, $http
you need to remove them from the parameter and also remove the return statement that was outside $http
which won't work anyway.
code
app.controller('mainCtrl', function() {
$scope.getUsersFromLocal = function() {
$http.get('http://localhost:8080/people').
success(function(data) {
$scope.data = data;
});
};
$scope.getUsersFromLocal(); //call ajax method
});
Try it like this, so I found it at w3school.
var app = angular.module('myApp4', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {
$scope.data= response.records;
});
});
If getUsersFromLocal
it is not a controller or service and you are calling this function manually, you must pass tags to it $http
and $scope
for example
module.controller('TestController', function($scope, $http) {
function getUsersFromLocal($scope,$http) {
$http.get('http://localhost:8080/people').
success(function(data) {
$scope.data = data;
});
}
getUsersFromLocal($scope, $http); // pass this services manually
});