【问题标题】:MEAN delete. Only working once意思是删除。只工作一次
【发布时间】:2015-08-20 19:51:15
【问题描述】:

我有一个非常简单的 MEAN 堆栈应用程序。我几乎完成了它,但是我有一个小错误。

当我去删除一行时,它会很好地删除。但是,当我尝试删除第二个或第三个等时,它只会将其从范围中删除。我必须先刷新才能再次在服务器端进行删除。

下面的 Angular 代码

  $scope.deleteNote = function(city){


     $http({
    method: 'DELETE',
    url: '/city',
    data: city.city,
    headers:{"Content-Type": "application/json;charset=utf-8"} });


    var index = $scope.cities.indexOf(city.city);
    var cityindex = city.city;



    console.log(cityindex + " at " + index);
    console.log(cityindex);
    console.log($scope);
    $scope.cities.splice(index, 1);

};

节点端代码

app.delete('/city', function(req,res){

CityDb.findOneAndRemove({city: req.body.city}, function(err, results){
    if (err) throw err;

});

});

那到底是怎么回事?

heroku 上的网站 https://serene-springs-2108.herokuapp.com/#/

github 获取完整代码

https://github.com/jminterwebs/STBExpress/tree/MEAN/Public/javascript

【问题讨论】:

    标签: angularjs node.js mean-stack


    【解决方案1】:

    我无法重现您在应用程序中遇到的错误(可能是因为现在有很多人正在从您的实时站点中删除内容!),但是您的服务器没有响应您的删除请求,这会导致控制台,也意味着您的角度前端可能会不同步。

    首先,在您的 express 应用中响应请求,如下所示:

    app.delete('/city', function(req,res){
    
      CityDb.findOneAndRemove({city: req.body.city}, function(err, results){
    
        if (err){
          res.status(500).send({error: err});
          // Assume you are going to catch this somewhere...
          throw err;
        }
    
        else
          res.status(200).send();
    
      });
    
    });
    

    其次,只有在确认删除成功后才将项目从您的角度范围中删除:

    $scope.deleteNote = function(city){
    
      // Make the request
      $http({
        method: 'DELETE',
        url: '/city',
        data: city.city,
        headers:{"Content-Type": "application/json;charset=utf-8"} 
      })
      // On success:
      .then(function (){
        var index = $scope.cities.indexOf(city.city);
        var cityindex = city.city;
        $scope.cities.splice(index, 1);
      })
      // On error:
      .catch(function (){
        // Do something better than this:
        alert("Something bad happened");
      })
    
      .finally(function (){
        // Re-enable the button.
        city.deleting = false;
      })
    
      // Disable the delete button and show a loading animation based on
      // this value (use `ng-disabled`).
      city.deleting = true;
    
    
    };
    

    以上内容将确保您的视图准确并与服务器上发生的情况保持一致。

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2017-08-01
      • 2016-09-07
      • 1970-01-01
      • 2019-01-19
      • 2017-01-06
      相关资源
      最近更新 更多