本文介绍了向json-server添加新对象; AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应该与json-server一起使用的角度应用程序,用于检索数据和添加新数据(用户反馈).所以我有一些数组的json数据库,其中之一是"feedbacks":[],当前为空.在PUT方法上我得到:

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来自服务器,这是Chrome控制台PUT http://localhost:3000/feedbacks 404 (Not Found).

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

这是我的服务

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

这是控制器:

    // 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()方法有效,服务器发送200,但是对于PUT,我收到404.

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

推荐答案

好的,我解决了:))一个非常愚蠢的错误.不需要推送然后更新,因为我想在数组内创建新对象.

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

我也将服务更改为:

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

为每个对象具有自动增量ID

to have auto incremental id for each object

这篇关于向json-server添加新对象; AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 23:58