简体   繁体   中英

angular factory $resource creating an empty object in database

I have created a REST application using angular $resource but i notice that everytime I make a put or post using a form...the $resource creates an empty entry(object) into database everytime there is a page reload which then displays in the frontend. This also happens when a post/put is not made but just a reload. I dont know if I am correctly using the $save function or is there something with my code

=========================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/>

===========================the factory==============================

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

================================the component========================

.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",

I've updated your component and service to make use of resource.$save() and $resource.remove() as following:

Updated Service

.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:"..."}]
      },
    });
  }
]);

Updated Component

.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"
});

The main problem which gave rise to the above problem was that the front page was still displays deleted(DELETE) data after a page refresh and also after an update (PUT) is made, the old content still displayed on page load. But I solve it my using headers: { "cache-control": "no-cache" }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM