角度:推,然后删除一个项目 [英] Angular: Push, then delete an item

查看:71
本文介绍了角度:推,然后删除一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用例:用户创建一个新任务,该任务必须通过API发送到上游.当该API返回成功时,我将其添加到显示范围.我的工作很好:

Use case: A user creates a new task, which has to be sent upstream through an API. When that API returns success, I add it to the scope for display. I have that working fine with:

$http.post('some_url', newtask).success(function(data) {
  $scope.tasks.push(data);
});

(newtask是之前定义的简单对象,此处未显示).

(newtask is a simple object defined earlier, not shown here).

问题是,API相当慢(尽管可靠),而我希望它看起来像一个实时应用程序.因此,我想立即将新任务推送到$ scope,然后在API返回成功时将其替换为真实"任务.因此,我在上面加上了

The problem is, the API is quite slow (though reliable), whereas I want this to feel like a real-time app. So I'd like to push the new task to the $scope immediately, then replace it with the "real" one when the API returns success. So I prepend the above with:

$scope.tasks.push(newtask); // Add to UI immediately (provisionally)

现在发生的是立即添加新任务,然后在API返回时添加任务的 second 副本.因此,我想做的就是在添加第二个副本后立即删除第一个副本.

What happens now is that the new task is added immediately, then a second copy of the task is added when the API returns. So what I'd like to do is remove the first copy as soon as the second copy is added.

我似乎找不到找到做到这一点的方法.还是我的方法全错了? (我承认,这种方法确实有点破烂,所以我愿意接受建议.)

I can't seem to find a find a way to do that. Or is my approach all wrong? (I admit, the approach does feel like a bit of a hack, so I'm open to suggestions).

推荐答案

在成功回调函数中,建议您将新任务(从API返回)与任务数组中的最后一个任务进行比较.如果它们匹配,则无需执行任何操作. (如果它们不匹配,则需要删除最后一项并抛出某种错误指示.)

In the success callback function, I suggest you compare the new task (coming back from the API) to the last task in your tasks array. If they match, you don't have to do anything. (If they don't match, you'll need to remove the last item and throw up some kind of error indication.)

$http.post('some_url', newtask).success(function(data) {
   if($scope.tasks[$scope.tasks.length-1] === data) {
      // do nothing, we already added it before
   } else {
     ... error handling here
   }
});

如果用户一次不能添加多个任务(在AP​​I返回之前),而您确实要删除然后添加,则只需对数组使用常规JavaScript操作删除最后一项,然后添加API值:

If the user can't add more than one task at a time (before the API returns), and you really want to remove then add, just use normal JavaScript operations on the array to remove the last item, then add the API value:

$http.post('some_url', newtask).success(function(data) {
    $scope.tasks.pop();
    $scope.tasks.push(data);
});

Angular应该会注意到模型的变化并自动为您更新视图.

Angular should notice the model change and automatically update the view for you.

这篇关于角度:推,然后删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆