Angular $resource create action undefined 不是对象

Angular $resource create action undefined is not an object

我有一个可用的 RESTful API,已使用 Postman 进行测试,并且 GET 端口也可以在我的应用程序中使用。

然而,当涉及到插入时,控制台出现以下错误:

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

我使用以下工厂进行创建操作:

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

以及以下控制器:

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

我通过路由将控制器传递到我的视图。我用一个按钮调用 addRecipe 操作,然后单击:

ng-click="addRecipe()

你能帮我解决这个问题吗?

基本上你错过了在你的控制器函数中注入 newrecipeService,所以在你的情况下 newrecipeService 是未定义的。对于这种情况,您必须在控制台中收到错误消息。

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

应该改为

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

编辑

要在服务器端获取数据,您需要更改对象属性以通过匹配属性名称在服务器端获取它们。

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