Search code examples
angularjsjsonangular-resourcejson-server

add new object to json-server; AngularJS


I have an angular app that supposed to work with json-server for retrieving data and adding new data (users feedback). so I have json database with some arrays and one of them is "feedbacks":[] which is currently empty. on PUT method I get:

PUT /feedbacks 404 from server and this is chrome console PUT http://localhost:3000/feedbacks 404 (Not Found).

this is my service:

angular.module('myApp')
        .constant("baseURL", "http://localhost:3000/")
.service('feedbackService',['$resource','baseURL',function($resource,baseURL){
      this.getFeedback=function(){
        return $resource(baseURL+"feedbacks/:date",null,{
          'update':{
            method:'PUT'
          }
        });
      };
    }]);

this is the controller:

    // contactus.html controllers
.controller('ContactController', ['$scope', function($scope) {
            $scope.feedback = {firstName: "",lastName: "",email: "",date: ""};
        }])
        // Feedback form controller
        .controller('FeedbackController', ['$scope', 'feedbackService', function($scope, feedbackService) {
            $scope.feedbacks = feedbackService.getFeedback().query(function(response) {
                $scope.feedbacks = response;
            });
            $scope.sendFeedback = function() {
                    $scope.feedback.date = new Date().toISOString();
                    $scope.feedbacks.push($scope.feedback);
                    feedbackService.getFeedback().update($scope.feedbacks);
                    $scope.feedbackForm.$setPristine();
                    $scope.feedback = {firstName: "",lastName: "",email: "", date:""};
            };
        }])

getFeedbacks() method works and server send 200, but for PUT I receive 404.


Solution

  • OK I solved it :)) a very silly mistake. there was no need for push and then update as I wanted to create new object inside the array.

    $scope.feedback.date = new Date().toISOString();
    feedbackService.getFeedback().save($scope.feedback);
    

    and also I changed the service to:

    return $resource(baseURL+"feedbacks/:id",null,{
    

    to have auto incremental id for each object