Javascript Angularjs $http.get 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29875703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs $http.get does not work
提问by emredmrl
My purpose is to consume a REST web service in AngularJS and I am making some trials right now. Below code is not working and throwing following exception. Can you help me identifty the problem?
我的目的是在 AngularJS 中使用 REST web 服务,我现在正在做一些试验。下面的代码不起作用并抛出以下异常。你能帮我找出问题吗?
Thanks in advance.
提前致谢。
function getUsersFromLocal($scope,$http)
{
$http.get('http://localhost:8080/people').
success(function(data) {
$scope.data = data;
});
return data;
}
Error is: TypeError: Cannot read property 'get' of undefined at getUsersFromLocal.
错误是:类型错误:无法在 getUsersFromLocal 读取未定义的属性“get”。
The service is accessible and I tested it through some REST clients.
该服务是可访问的,我通过一些 REST 客户端对其进行了测试。
采纳答案by Pankaj Parkar
If I understood correctly getUsersFromLocalfunction is inside controller, basically the function parameters are killing the $scope, $httpobject existence, You need to remove them from parameter & Also removed the return statement which was outside $httpwhich won't work in anyways.
如果我理解正确,getUsersFromLocal函数在控制器内部,基本上函数参数正在杀死$scope,$http对象存在,您需要将它们从参数中删除,并且还删除了外部的 return 语句,$http无论如何它都不起作用。
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
});
回答by sparsh610
Try like this , this way i found on w3school.
像这样尝试,这是我在 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;
});
});
回答by zegoline
if getUsersFromLocalis not a controller or service, and you are invoking this function manually, you should pass $httpand $scopeobjects to it, like this
如果getUsersFromLocal不是一个控制器或服务,而且你手动调用这个函数,你应该通过$http和$scope对象,就像这样
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
});

