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.
source to share
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
});
source to share
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
});
source to share