AngularJS service: gets error has no method 'save'

拜拜、爱过 提交于 2019-12-13 04:23:51

问题


I'm using AngularJS v1.0.7 and here's how I setup the service:

angular.module('myAngularJSApp.services',['ngResource'])
    .factory('RegisterNumber', ['$resource', function($resource) {
        return $resource( '../api/register/number/:id', {id:'@id'});
    }])
    .factory('RegisterChannel', ['$resource', function($resource) {
        return $resource( '../api/register/channel/:id', {id:'@id'});
    }])

and here's my controller:

angular.module('myAngularJSApp')
  .controller('RegisterCtrl', ['$scope', '$location', 'RegisterNumber', 'RegisterChannel', function ($scope, RegisterNumber, RegisterChannel) {

    $scope.step = 1;
    $scope.advanceStep = function(_step){
      var AcctNum = RegisterNumber
        , AcctChn = RegisterChannel

      switch(_step){
        case 1:
          var acctNum = AcctNum.save({ // This line throws the error
                          id : $scope.security_number 
                        },
                        // SUCCESS
                        function(){
                          $scope.showError = false;
                          advance(_step);
                        },
                        // ERROR
                        function(response){
                          $scope.showError = true;
                        });
          break;
        case 2:
          var acctChn = AcctChn.save(
                        { id : $scope.channel},
                        // SUCCESS
                        function(response){
                          $scope.showError = false;
                          advance(_step);
                        },
                        // ERROR
                        function(response){
                        });
          break;
      }
    }        
  }]);

And I get this error:

TypeError: Object #<Object> has no method 'save'
    at Object.$scope.advanceStep ...

I did some inspections: console.log(AcctNum) gives a LocationHashbangUrl object. However, strangely enough console.log(AcctChn) gives:

function Resource(value){
        copy(value || {}, this);
      }

which is correct. I have searched similar questions & tried the answers (here, here, and here) but I keep getting the same error. Did I miss something? Any thoughts?


回答1:


That's because you have wrong injection:

angular.module('myAngularJSApp')
  .controller('RegisterCtrl', 
    [
               '$scope', '$location',    'RegisterNumber', 'RegisterChannel', 
      function ($scope,   RegisterNumber, RegisterChannel) { ... }
    ]
  );

You're missing $location param in controller function signature.



来源:https://stackoverflow.com/questions/17544556/angularjs-service-gets-error-has-no-method-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!