AngularJs - `$ http`有效但是`$ resource`无效 - 如何将`$ http`参数应用于`$ resource`

时间:2016-01-05 04:50:36

标签: angularjs angular-resource angular-http

我正在尝试将图片信息发布到后端。我试过var messages = []; var obj = { err: { message: 'Validation failed', name: 'ValidationError', errors: { username: { properties: [Object], message: 'Path `username` is required.', name: 'ValidatorError', kind: 'required', path: 'username', value: '' } } } } for (var error in obj.err.errors.username) { if (error === "message") messages.push(obj.err.errors.username[error]) } console.log(messages)但没有工作。但是,当我尝试使用$resource时,它似乎有效。但我已经在$http添加了一些附加参数 - 但我不知道如何将这些$http应用于params,任何人都可以帮助我吗?

$resource

更新 - 我的新尝试

仍无效

$scope.photoData = function (photoData) {

         console.log( "photo data", photoData ); //consoles properly

        var fileData = photoData[0];
        var data = new FormData();

         var fileASHXPath =   _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';

         //this is not working!
         $resource(fileASHXPath).save({ "photoData" : fileData }).$promise.then( function ( response ) {

            console.log( response ); //nothing works!

         })

        //this is works!

         var base = _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';

         $http({
             url: base + 'TestImage.jpg',
             method: 'POST',
             processData: false,
             headers: { 'Content-Type': undefined },
             data: fileData
         }
                 )
                 .success(function (data) {

                     if (data.Message.toLowerCase() == 'success') {

                         console.log(data);
                     }                    

                 })
                 .error(function (msg, code) {

                     console.log('error method called');

                 });

     }

2 个答案:

答案 0 :(得分:1)

试试这个。那是在$ resource定义之后,用表单数据调用post()。

$scope.photoData = function (photoData) {

  console.log( "photo data", photoData ); //consoles properly

  var fd = new FormData();
  fd.append("photoData", photoData[0]);

  var fileASHXPath =   _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';

  $resource(fileASHXPath, {}, {
      post: {
        method: 'POST',
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }
    }
    ).post({}, fd).$promise.then(function ( response ) {

      console.log( "response is", response );

  });
});

答案 1 :(得分:0)

尝试调用资源。这是在$resource定义之后,请致电post()

    $resource(base + fileName, {}, {

        post:{
            method:"POST",
            isArray:false,
            headers:{'Content-Type':'undefined'}
        }

    }).post().$promise.then(function ( response ) {

        console.log( "response is", response );

    })