我试图从控制器中调用getStuff函数,但在控制台中收到一个错误,说"undefined不是函数"。我试图从GET返回JSON,然后将其存储在$scope变量中。
app.factory('UserInfo', function($http) {
var user = [];
return{
getStuff: function(){
user.push($http.get('api/users'));
return user;
},
testPost: function(){
return $http.post('api/users');
}
};
});
工厂与控制器连接如下
.controller('TwitterController', function($scope, $q, $interval, UserInfo) {
这是我用来调用工厂函数的$scope函数
$scope.datapls = function() {
UserInfo.getStuff().success(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}
谢谢!我很感激你的帮助。
您的错误指的是.success()
函数-它不存在。
看起来你在试图利用承诺。如果是这种情况,那么您需要从服务中return
承诺本身。
像这样的东西(没有经过测试,只是一个想法)。你想在你的服务中使用$q
,而不是你的柔术。
$q on AngularJS文档部分中的示例非常好。
因此,通过这样做,您的控制器不必等待数据。一旦解决
app.service('UserInfo', function($http, $q) {
this.getStuff = function(){
var deferred = $q.defer();
$http.get('api/users').success(function(data, status) {
deferred.resolve(data);
}).error(function(data, status) {
deferred.reject(data);
});
return deferred.promise;
}
}
);
在你的控制器中,你可以这样做:
UserInfo.getStuff().then(function(dataFromService){
// dataFromService is used in here..
$scope.loaduser.push(dataFromService);
}, function(error) {
// the error will come in via here
});
根据文档,$http本身返回一个承诺,您可以更改工厂功能以实现您想要做的事情:
app.factory('UserInfo', function($http) {
return{
getStuff: function(){
return $http.get('api/users'));
},
testPost: function(){
return $http.post('api/users');
}
};
});
在控制器中:
$scope.datapls = function() {
UserInfo.getStuff().then(function(response){
console.log(response);
$scope.loaduser.push(response);
});
}