angular factory $ resource在数据库中创建一个空对象

时间:2016-07-09 19:01:35

标签: javascript angularjs rest post

我使用angular $ resource创建了一个REST应用程序但是我注意到每次使用表单进行put或post时... $ resource会在每次有页面重新加载时创建一个空条目(对象)到数据库中显示在前端。当没有发布post / put但只是重新加载时也会发生这种情况。我不知道我是否正确使用$ save函数或者是否有我的代码

========================= HTML ===================== ====================

<div id="hello">
<div class='row'>
    <div class="col-md-6">
        <label for="content">Get greeting by ID:</label>
        <div>
            <input type='text' ng-model='$ctrl.getId' name="id" class="form-control"/>
            <span> {{ $ctrl.greeting.content }} </span>
        </div>
        <button ng-click='$ctrl.get();'>Get</button>
        <hr/>
        <div class="form-group">
            <label for="content">Post new Greeting:</label>
            <div>
                <textarea ng-model='$ctrl.postData' name="content" class="form-control"></textarea>
            </div>
            <button ng-click='$ctrl.post();'>Submit</button>
        </div>
        <hr/>
        <div class="form-group">
            <label for="content">Edit greeting by ID:</label>
            <div>
                <input type='text' ng-model='$ctrl.updateId' name="id" class="form-control"/>
            </div>
        </div>
        <div class="form-group">
            <div>
                <textarea ng-model='$ctrl.updateData' name="content" class="form-control"></textarea>
            </div>
            <button ng-click='$ctrl.put();'>Submit</button>
        </div>
        <hr/>
    </div>
    <div class="col-md-6">
        <hr/>
        <div class='row' ng-init="$ctrl.listAll()">
            <div ng-repeat="eachElement in $ctrl.greetingList.hello_collection">
                <div  class="col-md-2"> {{ eachElement.id }} </div>
                <div  class="col-md-5"> {{ eachElement.content }} </div>
                <div  class="col-md-5"><button ng-click="$ctrl.remove(eachElement.id)">delete</button></div>
            </div>
        </div>
    </div>
</div>
<hr/>

===========================工厂================== ============

.factory("helloService", ['$resource',
        function($resource) {
            return $resource('/direct/hello/:greetingId.json',
                { greetingId: '@greetingId' }, {
                get: {
                    method: 'GET',
                    params: {greetingId: '@greetingId'},
                    isArray: false
                },
                post: {
                    method: 'POST',
                    headers:{'Content-Type':'application/json; charset=UTF-8'},
                },
                put: {
                    method: 'PUT',
                    params: {greetingId: '@greetingId'}
                },
                remove: {
                    method: 'DELETE',
                    params: {greetingId: '@greetingId'}

                },
                listAll: {
                    method: 'GET',
                    isArray: false
                },
            });
        }
    ])

================================组件============= ===========

.component('hello', {
        controller: ['helloService',
            function (helloService) {
                var self = this;
                self.greetingList;
                function get() {
                    self.greeting = helloService.get({greetingId: self.getId});
                }
                self.get = get;

                function post() {
                    self.newGreeting = helloService.post({'content': self.postData }, function(data){
                        console.log(data);
                    });
                    self.greetingList.hello_collection.push(self.newGreeting);
                    self.postData = "";
                }
                self.post = post;

                function put() {
                    helloService.put({greetingId: self.updateId}, {'content': self.updateData });
                    var newValue = self.updateData;
                    var greeting = helloService.get({greetingId: self.updateId}, function(data){
                        data.content == newValue;
                        console.log(data);
                        console.log(data.content);
                    });
                    console.log(greeting);
                    /**
                    for (var i = 0; i < self.greetingList.hello_collection.length; i++)
                        {
                            if(self.greetingList.hello_collection[i].greetingId == self.updateId){
                                console.log(self.greetingList.hello_collection[i]);
                                self.greetingList.hello_collection[i].content = self.updateData;
                            }
                        }
                    **/
                    self.updateId, self.updateData = "";                            
                }
                self.put = put;

                function remove(deleteId) {
                    var greeting = helloService.get({greetingId: deleteId})
                    for (var i = 0; i < self.greetingList.hello_collection.length; i++) {
                        if (self.greetingList.hello_collection[i]["id"] == deleteId) {
                            var index = i;
                            break;
                        }
                    }
                    if (index >= 0) {
                        self.greetingList.hello_collection.splice(index, 1);
                        helloService.remove({greetingId: deleteId}, function() {
                          greeting.$delete();
                        });                         
                    }                       
                }
                self.remove = remove;
                var greetingList;
                function listAll() {
                    self.greetingList = helloService.listAll();
                }
                self.listAll = listAll;
                var newService = new helloService();
                newService.$save();

            }
        ],
        templateUrl: "./templates/hello.html",

2 个答案:

答案 0 :(得分:1)

我已更新您的组件和服务以使用资源。$ save()和$ resource.remove()如下:

更新服务

.factory("helloService", ['$resource',
  function($resource) { 
    return $resource('/direct/hello/:greetingId.json', {
      greetingId: '@greetingId'
    }, {
      get: {
        method: 'GET', 
        params: {
          greetingId: '@greetingId'
        }, 
        isArray: false
      },
      post: {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8'
        },
      },
      put: {
        method: 'PUT',
        params: {
          greetingId: '@greetingId'
        }
      },
      remove: {
        method: 'DELETE',
        params: {
          greetingId: '@greetingId'
        }

      },
      listAll: {
        method: 'GET',
        isArray: true // <-- this should be true as in a RESTFULL app the
                      //     listAll should expect array of objects as a 
                      //     response i.e.: [{id:1,content:"..."},
                      //     {id:2,content:"..."}]
      },
    });
  }
]);

更新了组件

.component('hello', {
        controller: ['helloService',
            function (helloService) { 
                var self = this;

                function get() {
                    self.greeting = helloService.get({greetingId: self.getId});
                }
                self.get = get; 

                function post() {
                    var greetingItem = new helloService();
                    greetingItem.content = self.postData;
                    greetingItem.$save();
                    self.greetingList.push(greetingItem);
                    self.postData = "";
                }
                self.post = post;

                function put() {
                    var greetingItem = helloService.get({greetingId: self.updateId}, function() {
                      greetingItem.content = self.updateData;
                      greetingItem.$save();
                      console.log(greetingItem);
                      self.updateId = "";
                      self.updateData = "";         
                    });

                }
                self.put = put;

                function remove(deleteId) {
                    var greetingItem = helloService.get({greetingId: deleteId}, function(){
                      for (var i = 0; i < self.greetingList.length; i++) {
                          if (self.greetingList[i].id == deleteId) {
                              var index = i;
                              break;
                          }
                      }
                      greetingItem.$delete({greetingId: deleteId});
                      if (index >= 0) {
                          self.greetingList.splice(index, 1);
                      }                       
                    });
                }
                self.remove = remove;

                var greetingList = [];
                function listAll() {
                    self.greetingList = helloService.listAll();
                }
                self.listAll = listAll;

            }
        ], 
        templateUrl:  "./templates/hello.html"
});

答案 1 :(得分:0)

引起上述问题的主要问题是在页面刷新之后以及在更新(PUT)之后,首页仍显示已删除(DELETE)数据,旧内容仍显示在页面加载上。但是我使用标题来解决它:{&#34; cache-control&#34;:&#34; no-cache&#34; }

angular.module('helloApp', ['ngResource'])
    .factory("helloService", ['$resource',
        function($resource) {
            return $resource('/direct/hello/:greetingId.json',
                { greetingId: '@greetingId' }, {
                get: {
                    method: 'GET',
                    params: {greetingId: '@greetingId'},
                    isArray: false,
                    headers: { "cache-control": "no-cache" }
                },
                post: {
                    method: 'POST',
                    headers:{'Content-Type':'application/json; charset=UTF-8'},
                },
                put: {
                    method: 'PUT',
                    params: {greetingId: '@greetingId'},
                    headers: { "cache-control": "no-cache" }
                },
                remove: {
                    method: 'DELETE',
                    params: {greetingId: '@greetingId'}
                },
                listAll: {
                    method: 'GET',
                    isArray: false,
                    headers: { "cache-control": "no-cache" }
                },
            });
        }
    ])