Search code examples
angularjsangular-resource

Angular $resource create action undefined is not an object


I have a working RESTful API, tested with Postman and also the GET port works within my app as well.

However when it comes to inserting it fails with the following error in the console:

Error: undefined is not an object (evaluating 'newrecipeService.create')

I use the following factory for the create action:

app.factory('newrecipeService', function ($resource) {
  return $resource('/api/recipes/', {}, {
   create: {method: 'POST'}
  });
});

And the following controller:

app.controller('FormController', ['$scope',function($scope,newrecipeService){
  $scope.addRecipe = function() {
    newrecipeService.create({name: 'Test', nameID: 'test', category: 'TestCat', categoryID: 'testcat'});
  };
}]);

I pass the controller to my view with a route. I call the addRecipe action with a button and ng-click:

ng-click="addRecipe()

Could you please help me out on this?


Solution

  • Basically you had missed to inject newrecipeService in your controller function, so in your case newrecipeService is undefined. You must have getting error in console for this case.

    app.controller('FormController', ['$scope',function($scope,newrecipeService){
    

    should be changed to

    app.controller('FormController', ['$scope', 'newrecipeService' ,
        function($scope,newrecipeService){
    

    Edit

    For getting data on server side you need to change the object properties to get them up on server side by matching properties name.

    app.controller('FormController', ['$scope',function($scope,newrecipeService){
      $scope.addRecipe = function() {
        newrecipeService.create({
           newRecN‌​ame: 'Test', 
           newRecNameID: 'test', 
           newRecCategory: 'TestCat', 
           newRecIngredients: 'someIngredients',
           newRecMethod: 'someRecMethod'
        });
      };
    }]);