Angularjs 如何使用transformRequest和transformResponse修改$resource的数据?

Angularjs 如何使用transformRequest和transformResponse修改$resource的数据?,angularjs,coffeescript,Angularjs,Coffeescript,我使用的是兼容的API,格式要求之一是所有数据(传入和传出)必须包装在数据对象中。所以我的请求看起来像: { "data": { "email": "email@example.com", "password": "pass", "type": "sessions" } } { "data": { "user_id": 13, "expires": 7200, "token": "gpKkNpSIzxrkYbQiYxc6us0yDeq

我使用的是兼容的API,格式要求之一是所有数据(传入和传出)必须包装在
数据
对象中。所以我的请求看起来像:

{
  "data": {
    "email": "email@example.com",
    "password": "pass",
    "type": "sessions"
  }
}
{
  "data": {
    "user_id": 13,
    "expires": 7200,
    "token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
  }
}
angular.module('webapp').factory 'Session', [
  '$resource'
  ($resource) ->
    $resource 'http://localhost:9500/v1/sessions',
      id: '@id'
    ,
      save:
        method: 'POST'
        transformRequest: (data) ->
          result =
            data: JSON.parse JSON.stringify data
          result.data.types = 'sessions'
          result = JSON.stringify result
          result
        transformResponse: (data) ->
          result = JSON.parse data
          a = JSON.parse JSON.stringify result.data
          console.log a
          a
我的回答是:

{
  "data": {
    "email": "email@example.com",
    "password": "pass",
    "type": "sessions"
  }
}
{
  "data": {
    "user_id": 13,
    "expires": 7200,
    "token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
  }
}
angular.module('webapp').factory 'Session', [
  '$resource'
  ($resource) ->
    $resource 'http://localhost:9500/v1/sessions',
      id: '@id'
    ,
      save:
        method: 'POST'
        transformRequest: (data) ->
          result =
            data: JSON.parse JSON.stringify data
          result.data.types = 'sessions'
          result = JSON.stringify result
          result
        transformResponse: (data) ->
          result = JSON.parse data
          a = JSON.parse JSON.stringify result.data
          console.log a
          a
在控制器中,当发出新会话请求时,我有:

$scope.signin = ->
  session = new Session
    email: $scope.user.email
    password: $scope.user.password

  session.$save()

  console.log session
  console.log session.token
  if not session.token
    alert 'Invalid Login'
  else
    $rootScope.session_token = session.token
    $state.go 'app.dashboard'
我的
会话
是一个工厂,看起来像:

{
  "data": {
    "email": "email@example.com",
    "password": "pass",
    "type": "sessions"
  }
}
{
  "data": {
    "user_id": 13,
    "expires": 7200,
    "token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
  }
}
angular.module('webapp').factory 'Session', [
  '$resource'
  ($resource) ->
    $resource 'http://localhost:9500/v1/sessions',
      id: '@id'
    ,
      save:
        method: 'POST'
        transformRequest: (data) ->
          result =
            data: JSON.parse JSON.stringify data
          result.data.types = 'sessions'
          result = JSON.stringify result
          result
        transformResponse: (data) ->
          result = JSON.parse data
          a = JSON.parse JSON.stringify result.data
          console.log a
          a
这个要求很好。格式化和解析似乎很有效。但是,当I
log
时,响应显示为
资源
,而不是
对象
。即使服务器返回有效数据,
session.token
也显示为未定义


我如何修改我的
transformResponse
来解释这一点?

我认为您想要的是用承诺捕获您的资源响应:

session.$save().$promise.then(function (result) {
    console.log (result);
});

我可以推荐一个XHR拦截器吗

xhrInterceptor.js

(function (app) {
    "use strict";

    function XhrInterceptor($q) {
        return {

            request: function requestInterceptor(config) {
                var data = config.data;

                if (data &&
                    config.method === "POST") {

                    config.data = {
                        data: data
                    };
                }

                return config || $q.when(config);
            },

            response: function responseInterceptor(response) {
                if (typeof response === "object") {
                    if (response.config.method === "POST") {
                        response.data = response.data.data || {};
                    }
                }

                return response || $q.when(response);
            }
        };
    }

    app
        .factory("app.XhrInterceptor", ["$q", XhrInterceptor]);

})(window.app);
app.js

(function (app) {
    "use strict";

    function XhrInterceptor($q) {
        return {

            request: function requestInterceptor(config) {
                var data = config.data;

                if (data &&
                    config.method === "POST") {

                    config.data = {
                        data: data
                    };
                }

                return config || $q.when(config);
            },

            response: function responseInterceptor(response) {
                if (typeof response === "object") {
                    if (response.config.method === "POST") {
                        response.data = response.data.data || {};
                    }
                }

                return response || $q.when(response);
            }
        };
    }

    app
        .factory("app.XhrInterceptor", ["$q", XhrInterceptor]);

})(window.app);
在配置阶段或其他初始化逻辑中,添加响应拦截器

app
    .config(["$httpProvider", function ($httpProvider) {
            $httpProvider.interceptors.push("app.XhrInterceptor");
    });
进一步信息


data:JSON.parse JSON.stringify data
为什么这样做?您需要了解
会话。$save()
是异步的,因此
console.log会话。令牌将立即被调用,并且在
会话之前一直未定义。$save()
请求得到解决。我尝试使用了
。然后也使用了
承诺,出现了相同的结果
。然后除非您返回承诺,否则
将无法帮助您。资源自动行为与承诺不同。在解决承诺之前,您的响应将作为资源登录。与session.token相同,因为javascript不会自动等待异步请求解析。请添加资源定义的其余部分。我意识到,我从未看到您从资源中返回的内容。它也可能被更改为
会话。$save(函数(结果){//successCallback})