TypeError: undefined is not a function in Angular Resource

后端 未结 3 1491
一生所求
一生所求 2020-12-11 06:36

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy wo

相关标签:
3条回答
  • 2020-12-11 06:43

    The answer from Guido is correct but I didn't get it at the first time.

    If you add a custom method to your Angular $resource and using isArray: true and expecting to get an Array of something from your WebService you probably want to store the response in an Array.

    Therefore you shouldn't use the instance method like this:

    var ap = new Ansprechpartner();
    $scope.nameDuplicates = ap.$searchByName(...);
    

    But use the resource directly:

    $scope.nameDuplicates = Ansprechpartner.searchByName(...)
    

    Using following Angular resource:

    mod.factory('Ansprechpartner', ['$resource',
        function ($resource) {
            return $resource('/api/Ansprechpartner/:id', 
                { id: '@ID' },
                {
                    "update": { method: "PUT" },
                    "searchByName": { method: "GET", url: "/api/Ansprechpartner/searchByName/:name", isArray: true }
                }
            );
        }
    ]);
    
    0 讨论(0)
  • 2020-12-11 06:47

    I am using Mean.js and this plagued for a few hours. There is a built in $update but it was not working when I tried to apply it to an object returned by a $resource. In order to make it work I had to change how I was calling the resource to update it.

    For example, with a Student module, I was returning it with a $resource into $scope.student. When I tried to update student.$update was returning this error. By modifying the call to be Students.update() it fixed the problem.

     $scope.update = function() {
       var student = $scope.student;
       var result = Students.update(student);
    
       if(result){
          $scope.message = 'Success';
       } else {
          $scope.error = 
            'Sorry, something went wrong.';
       }
     };

    0 讨论(0)
  • 2020-12-11 06:58

    I found the answer:

    A resource is supposed to represent the matched data object for the rest of its lifespan. If you want to fetch new data you should do so with a new object.

    $scope.copies = ContentPage.copies()
    
    0 讨论(0)
提交回复
热议问题