AngularJS $ Resource - 即使服务器返回HTTP 200响应,回调总是触发错误功能

时间:2014-01-09 12:43:36

标签: angularjs angularjs-resource

我使用$ resource使用REST服务。为什么即使我从服务器获得Http:200(Ok)响应,总是会触发错误回调函数?我尝试了两种设置回调函数的方法,两者都有相同的问题。

这是我使用服务的Angular控制器:

appRoot
.controller(
    'BatchTaskController',
    ['$scope', 'batchTaskService', function ($scope, batchTaskService){

    $scope.runImportIntermediariesTask = function () {
        batchTaskService.runImportIntermediariesTask().$promise.then(
            function (value) { alert('success') },
            function (error) { alert('error') }
            );
    };

    $scope.runImportVantageTransactionsTask = function () {
        batchTaskService.runImportVantageTransactionsTask(
            function () { alert('success'); },
            function () { alert('error'); }
            );
    };

    $scope.runProcessVantageTransactionsTask = function () { batchTaskService.runProcessVantageTransactionsTask(); };
}]);

这是Angular服务:

var angularVectorServices = angular.module('angularVector.services', ['ngResource']);

angularVectorServices.factory('batchTaskService', ['$resource' , function ($resource) {
return $resource(
    "http://localhost:58655/api/BatchTask/:action",
    {
        action: "@action"
    },
    {
        runImportIntermediariesTask: {
            method: "POST",
            params: {
                action: "RunImportIntermediariesTask"
            }
        },

        runImportVantageTransactionsTask: {
            method: "POST",
            params: {
                action: "RunImportVantageTransactionsTask"
            }
        },

        runProcessVantageTransactionsTask: {
            method: "POST",
            params: {
                action: "RunProcessVantageTransactionsTask"
            }
        }
    }
);
}]);

我正在使用WebApi。这是Server ApiController代码:

public HttpResponseMessage RunImportIntermediariesTask()
    {
      //  _importIntermediariesTask.Run();

        var response = Request.CreateResponse(HttpStatusCode.OK);

        return response;
    }

    public HttpResponseMessage RunImportVantageTransactionsTask()
    {
        //_importVantageTransactionsTask.Run();

        var response = Request.CreateResponse(HttpStatusCode.OK);

        return response;
    }

1 个答案:

答案 0 :(得分:0)

以此为样本,尝试按照下面的操作进行操作,在 HttpStatusCode.Whatever 上设置代码响应代码:

public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
         return new HttpResponseMessage(HttpStatusCode.NotModified);
    }
    return request.CreateResponse(HttpStatusCode.OK, user);
}

希望这有帮助。