ng-resource参数化url不适用于发布

时间:2015-02-27 21:27:46

标签: angularjs

当我尝试保存此资源时,最终被调用的网址是:http://localhost:8080/api/apps/configs。当我将保存更改为get时,它可以正常工作。

$scope.appconfig = {}
/**
* save the current configuration
*/
$scope.saveConfig = function() {

var Config = $resource('api/apps/:appid/:version/:env/:site/configs');

Config.save({
    appid : sel.app.name,
    version : sel.version,
    env : sel.env.name,
    site: sel.site.id,
    configs: $scope.appconfig
}, function(resp) {
    console.log(resp);
})

}

1 个答案:

答案 0 :(得分:0)

您需要提供映射,如下所示:

var Config = $resource('api/apps/:appid/:version/:env/:site/configs', {
  appid: '@appid',
  version: '@version',
  env: '@env',
  site: '@site',
  configs: '@configs'
});

再次更新:

你要求的是什么,有点违背ngResource模式,但这应该可以解决问题。

var app = angular.module('plunker', ['ngResource']);

app.controller('MainCtrl', function($scope, Config) {
  $scope.name = 'World';

  $scope.appconfig = {
    purple: 'monkey',
    dishwasher: true
  };

  var sel = {
    app: {
      name: 'foo'
    },
    version: '0.0.1',
    env: {
      name: 'bar'
    },
    site: {
      id: '1234-5678-90'
    }
  };

  /**
   * save the current configuration
   */
  $scope.saveConfig = function() {
    Config.save({
      appid: sel.app.name,
      version: sel.version,
      env: sel.env.name,
      site: sel.site.id,
      configs: $scope.appconfig
    }).then(function(resp) {
      console.log(resp);
    }, function(err) {
      console.log(err);
    });

  };
});

app.factory('Config', function($http, $resource) {
  return $resource('api/apps/:appid/:version/:env/:site/configs', {
      appid: '@appid',
      version: '@version',
      env: '@env',
      site: '@site'
    }, {
      save: {
        method: 'POST',
        transformRequest: [function(request) {
          return {
            configs: request.configs
          };
        }].concat($http.defaults.transformRequest)
      }
    });
});

以下是一名演示者:http://plnkr.co/edit/BBwkxPyU6kQ0FLYzzb3V?p=preview