ng资源 使用$delete从查询对象中删除记录

ngResource remove record from query object with $delete

本文关键字:对象 删除 记录 查询 资源 使用 delete ng      更新时间:2023-09-26

对角度来说相当新。我想使用 angular 的$resource库来使用我们的 API 服务。我对删除通过 query() 方法获得的记录的正确方法有点迷茫。具体来说,我们有一个用于用户通知的终结点。我们希望在页面加载时获取所有用户通知,使用 ng-repeat 循环查看结果并在导航栏中显示通知。当用户单击删除图标时,应删除相应的通知。这是我目前拥有的代码的精简版本:

Js:

angular.module('myapp', ['ngResource']).factory('Notifications',function($resource){
    return $resource('/apiv2/user/notifications/:id', {id:'@id'});
}).controller('NavigationController',['$scope','Notifications',function($scope, Notifications){
    $scope.notifications = Notifications.query();
    $scope.deleteNotification = function(notification){
        notification.$delete();
    };
}]);

.HTML:

<ul>
    <li ng-repeat="notification in notifications">
        <i class="icon-remove" ng-click="deleteNotification(notification)"></i>
    </li>
</ul>

使用此代码,当用户单击删除图标时,单个通知对象将传递到 deleteNotification 方法,并通过 API 从后端正确删除。到目前为止,一切都按预期进行。但是,如果我事后查看 $scope.notifications 对象,刚刚删除的通知仍然包含损坏的数据:

{$promise:未定义, $resolved:true}

理想情况下,我希望从通过 .query() 方法返回的对象中擦除此记录以反映其在后端的状态,而无需执行新的 .query()。

任何帮助将不胜感激!对于模糊的描述和/或不完整/不准确的代码,我深表歉意,我在晚餐时通过手机键盘从内存中输入了这一切,所以天知道我是否错过了什么。

更好的方法:(参见 AngularJS ngResource delete 事件)

$scope.deleteNotification = function (index) {
  $scope.notifications[index].$delete();
  $scope.notifications.splice(index, 1);
}

在你的标记中,只需做

ng-click="deleteNotification($index)"

可能有更好的方法可以做到这一点,因为这会引发控制台错误(但仍然有效),但这就是我正在做的事情:

$scope.notifications = Notifications.query();
$scope.deleteNotification = function(notification){
    notification.$delete();
    $scope.notifications = $scope.notifications.filter( function(n)
        return (n != notification);
    }); // filter everything but
};

如果你使用下划线,有一种更漂亮的方法来编写删除的东西。