【问题标题】:Insert value into db.json with help of angular-resource在 angular-resource 的帮助下将值插入 db.json
【发布时间】:2016-01-17 16:37:41
【问题描述】:

我有一个名为 db.json 的 json 文件,类似于

{
"menu":[
 {
   "id":0,
   "item":"item1"
},{
   "id":1,
   "item":"item2"
},{
   "id":2,
   "item":"item3"
}
],
"feedback":[]
}

我在feedback 数组中使用了角度$resourcePUT 的Javascirpt 对象。

这是我的服务代码-

this.getFeedbacks = function(){
            return $resource(baseURL + "feedback/:id", null, {
                'update': {
                    method: 'PUT'
                }
            });
        };

这是控制器代码-

$scope.fb.push($scope.myFeedback);
 menuFactory.getFeedbacks().update({
            id: $scope.fb.id
        }, $scope.fb);

请注意,json 中的 feedback 数组是空的,并且 $scope.myFeedback 是从 ng-controller 的 ng-model 中找到的,当我单击提交按钮时,这个 ng-controller 有一个提交按钮,然后是值的输入存储到 json 文件中。
HTML代码是-

<form name="feedbackForm" ng-submit="setFeedback()">
   <input type="text" name="name" ng-model="myFeedback.name">
   <input type="submit" name="submit" value="feedback">
</form>

我的更新功能不起作用,为什么请有人解释一下。 请注意,我是 angularJS 平台和 REST 客户端-服务器网络的初学者。

【问题讨论】:

  • 能否提供一个小提琴以便更好地理解?
  • 您不能将数据发布到静态资源文件。该文件只能由服务器端编程语言修改。 baseUrl 的值是多少?
  • 我说我是这个领域的初学者。我只想将值保存在从名称文本字段中找到的 json 文件中。
  • 你的服务器运行的是什么编程语言?
  • 我正在使用 json-server

标签: javascript angularjs json rest angular-resource


【解决方案1】:

我相信这是 Coursera 的一个练习。这是我的解决方案。

您应该使用 $resource 中的 'save' 方法将数据添加到 db,json 文件中,而不是使用“更新”。

在你的控制器中,说:

menuFactory.getFeedbacks().save($scope.feedback);

$scope.feedback 应该是您在反馈表单对象中使用的名称

希望这个答案对你有所帮助!

【讨论】:

  • 并且你的服务中的代码可以简化成这样(不需要使用自定义的PUT请求):
    this.getFeedbacks = function(){ return $resource(baseURL + "feedback" ); };
【解决方案2】:

首先,观察浏览器控制台。它经常给你提示,在哪里寻找错误。回到问题上来:尝试使用$update 而不是update

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多