AngulrJS $资源获取错误 - undefined不是函数

时间:2017-01-05 17:05:43

标签: javascript angularjs

 var app1 = angular.module('app1',['ngResource']);

app1.factory("Users", function($resource) {
  return $resource("http://10.130.36.132:8010/users/:_id");
});

app1.controller('ctrl1',function($scope,Users) {

       $scope.sendRequest = function(){
            Users.query(function(data){
                $scope.users = data;
            });

            Users.get({_id: 22},function(data){
                $scope.user = data;
            })
       };


});

在上面的代码中调用Users.get时出现以下异常:

TypeError: undefined is not a function
    at file:///android_asset/www/js/angular-resource.js:576:30
    at forEach (file:///android_asset/www/js/angular.js:330:18)
    at Object.Route.setUrlParams (file:///android_asset/www/js/angular-resource.js:570:11)
    at Function.Resource.(anonymous function) (file:///android_asset/www/js/angular-resource.js:738:19)
    at Scope.$scope.sendRequest (file:///android_asset/www/js/res_test2.js:14:19)
    at fn (eval at <anonymous> (file:///android_asset/www/js/angular.js:14539:15), <anonymous>:4:224)
    at expensiveCheckFn (file:///android_asset/www/js/angular.js:15628:18)
    at callback (file:///android_asset/www/js/angular.js:25172:17)
    at Scope.$eval (file:///android_asset/www/js/angular.js:17378:28)
    at Scope.$apply (file:///android_asset/www/js/angular.js:17478:25)angular.js:13642 (anonymous function)

1 个答案:

答案 0 :(得分:0)

 app1.controller('ctrl1', ['$scope', 'Users', function($scope,Users) {
     $scope.sendRequest = function(){
        Users.query(function(data){
            $scope.users = data;
        });

        Users.get({_id: 22},function(data){
            $scope.user = data;
        })
     };
 }]);  

您错过了添加依赖项。只需添加,您的工厂也如下

 app1.factory("Users", ['$resource', function($resource) {
   return $resource("http://10.130.36.132:8010/users/:_id");
 }]);