Question

I have a fairly simple AngularJS app that is consuming a Spring MVC Rest API.

I am able to query the API. But I am having trouble Creating objects. I get the following error and have not been able to figure out why. I have looked at similar questions but my API is returning the created object and from what I can tell my injections are correct.

Here is the stack from the javascript console:

TypeError: Object #<Resource> has no method 'save'
at Object.TeamListCtrl.$scope.addPlayer(http://localhost:8000/app/js/controllers.js:17:13)
at elementFns (http://localhost:8000/app/lib/angular/angular.js:6365:19)
at Object.$get.Scope.$eval (http://localhost:8000/app/lib/angular/angular.js:8057:28)
at Object.$get.Scope.$apply (http://localhost:8000/app/lib/angular/angular.js:8137:23)
at Object.ng.config.$provide.decorator.$delegate.__proto__.$apply (http://localhost:8000/app/index.html:855:30)
at HTMLFormElement.ngIncludeDirective.restrict (http://localhost:8000/app/lib/angular/angular.js:13159:11)
at event.preventDefault (http://localhost:8000/app/lib/angular/angular.js:1992:10)
at Array.forEach (native)
at forEach (http://localhost:8000/app/lib/angular/angular.js:130:11)
at HTMLFormElement.eventHandler (http://localhost:8000/app/lib/angular/angular.js:1991:5) 

Here is my controller:

function TeamListCtrl($scope, Shared, Teams, Players) {
$scope.teams = Teams.query();

$scope.addPlayer = function() {

    var newPlayer = new Players({
        position: $scope.newPlayer.position,
        lastName: $scope.newPlayer.lastName,
        firstName: $scope.newPlayer.firstName
    });

    newPlayer.save({teamId: $scope.newPlayer.teamId});
};
}

TeamListCtrl.$inject = ['$scope', 'Shared', 'Teams', 'Players'];

Here is my service:

var teamsService = angular.module('teamsService', ['ngResource']);

teamsService.factory('Players', function($resource){
    return $resource('http://localhost\\:8080/api/teams/players/:teamId', {teamId:'@teamId'}, {
        save: {method:'POST'}
    });
});

Thank you for any help you can provide.

Was it helpful?

Solution

Can you try to post the resource, like this

var newPlayer = {
        teamId: $scope.newPlayer.teamId,
        position: $scope.newPlayer.position,
        lastName: $scope.newPlayer.lastName,
        firstName: $scope.newPlayer.firstName
    };

Players.save(newPlayer);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top