TypeError: undefined is not a function in Angular Resource

独自空忆成欢 提交于 2019-11-28 12:24:35
Guido Bouman

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()

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 }
            }
        );
    }
]);

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