使用$ resource从AngularJs中的Web API访问HttpResponseMessage

时间:2016-03-01 20:24:20

标签: c# angularjs angular-promise angular-resource

我有一个c#web api方法,它将整数值返回为HttpResponseMessage,想要使用$ resource从AngularJs中的响应访问相同的内容,怎么做?

Web API:

[HttpPut]
        [Route("DeleteFile")]
        public HttpResponseMessage DeleteFile(int cabinetFileID)
        {
            var fileName = cabinetDataAccess.GetFilePath(cabinetFileID);                  
                var returnVal = cabinetDataAccess.DeleteCabinetFile(cabinetFileID, UserEmail);
                return Request.CreateResponse(HttpStatusCode.OK, returnVal);                

        }

服务:

(function () {
    'use strict';

    angular
        .module('data')
        .factory('cabinetService', cabinetService);

    cabinetService.$inject = ['$resource', 'serviceBase'];

    function cabinetService($resource, serviceBase) {
            var deleteCabinetFileResource = $resource(serviceBase + '/api/Cabinet/DeleteFile?cabinetFileID=:cabinetFileID',null,{'update':{method:'PUT'}});

        return {                
            deleteCabinetFile: deleteCabinetFile
        };

        function deleteCabinetFile(cabinetFileID){
            return deleteCabinetFileResource
                .update({cabinetFileID:cabinetFileID},null)
                .$promise;
        }
    }
}());

控制器:

function deleteThumbnail(cabinetFileID)
        {
           cabinetService
            .deleteCabinetFile(cabinetFileID)
            .then(function (data) {
                //How do i Access my return value here ???
                //Something like 
                if(data.returnVal === -1)
                //do something
            })
            .catch(function (err) {
                growl.err('Unable to delete  file, Please try later !', {ttl: 20000});
            })
        }

这段代码让我得到了回复,我如何从数据中获取返回值?

1 个答案:

答案 0 :(得分:0)

基于https://stackoverflow.com/users/5535245/georgeawg注释更改了我的c#代码,如下所示返回一个Json对象,一切运行良好。

    [HttpPut]
            [Route("DeleteFile")]
            public JObject DeleteFile(int cabinetFileID)
            {
                var fileName = cabinetDataAccess.GetFilePath(cabinetFileID);                  
                    var returnVal = cabinetDataAccess.DeleteCabinetFile(cabinetFileID, UserEmail);
 var jsonString = Json(new JavaScriptSerializer().Serialize(new { returnVal }));
                return JObject.Parse(jsonString.Content);      
            }

在我的AngularJs控制器中,我可以检查if(data.returnVal === -1)