【问题标题】:delete with webapi and angular-resource使用 webapi 和 angular-resource 删除
【发布时间】:2015-12-03 14:38:00
【问题描述】:

我正在尝试使用 angular-resource en asp.net webapi 删除我的集合中的一个项目。调用了正确的服务器端方法,但没有发送任何对象:手提箱为空。

我在负责发送对象的代码中遗漏了什么?

角码:

var myApp = angular.module('myApp', ['ui.router', 'ngResource']);

        myApp.config([
            '$stateProvider', function($stateProvider) {
                $stateProvider
                    .state('suitcases.delete', {
                        url: '/suitcase/delete/:id',
                        controller: 'deleteSuitcaseController'
                    });
            }
        ]);

angular.module('myApp').controller('deleteSuitcaseController', function ($scope, $state, $stateParams, Entry) {
            console.log('deleteSuitcaseController', $stateParams.id);

            $scope.deleteSuitcase = function () {
                var suitcase = Entry.get({ id: $stateParams.id });
                suitcase.$delete();
            };

            $scope.deleteSuitcase();
        });

angular.module('myApp').factory('Entry', function($resource) {

            return $resource(
                "api/suitcaseapi/:id", { id: '@@id' },
                { "update": { method: "PUT" } },
                { "add": { method: "POST" } }
            );
        });

webapi 代码:

public class SuitcaseApiController : ApiController
    {
public void Delete(Suitcase suitcase)
        {
            Singleton.Instance.Suitcases.RemoveAll(p => p.Id == suitcase.Id);
        }
    }

如果我将服务器端方法更改为下面的代码,我会在浏览器中收到 405 not allowed 错误。

    public void Delete(int suitcaseid)
        {
            Singleton.Instance.Suitcases.RemoveAll(p => p.Id == suitcaseid);
        }
    }

PS。我把我认为无关紧要的代码拿出来了。

【问题讨论】:

  • 入口在工厂中定义。查看更新的代码示例。

标签: c# angularjs asp.net-web-api angular-resource


【解决方案1】:

如果是删除,并且我可以看到您已经拥有了 suitcaseId,那么您不需要调用 API 来返回整个对象来删除它。只需传递 ID,API 就会负责查找实体。像这样的:

角度控制器/功能

angular.module('myApp').controller('deleteSuitcaseController', function ($scope, $state, $stateParams, Entry) {

    $scope.entity.id = $stateParams.id;

    $scope.deleteSuitcase = function () {

        $http.delete('/Suitcase/' + $scope.entity.id)
        .success(function (data, status, headers) {

        })
        .error(function (data, status, header, config) {
        });
    }
});

删除方法 API

public void Delete(int id)
{   
    Singleton.Instance.Suitcases.RemoveAll(p => p.Id == id);
}

【讨论】:

  • 这个例子不起作用,因为 $http 和 $scope.entity 没有定义。如果我解决了这个问题,我会得到一个不允许的方法 (405) 错误。这与我将示例中的服务器端方法更改为 public void Delete(int id) 时遇到的错误相同。除此之外,这个解决方案没有使用资源库,可能我还不清楚:我的目标是为此使用 angular-resource。
  • 好吧,我只提供了代码外观的示例。我不知道您正在使用哪些库或资源,所以我尝试创建一个通用代码,以便您想象这个想法。在你的问题中你没有指定你得到 405 错误..
猜你喜欢
  • 1970-01-01
  • 2014-12-12
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多