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

How do I use transformRequest and transformResponse to modify data for a $resource?

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

{
  "data": {
    "email": "email@example.com",
    "password": "pass",
    "type": "sessions"
  }
}

我的回复如下:

{
  "data": {
    "user_id": 13,
    "expires": 7200,
    "token": "gpKkNpSIzxrkYbQiYxc6us0yDeqRPNRb9Lo1YRMocyXnXbcwXlyedjPZi88yft3y"
  }
}

在我的控制器中,当发出新的会话请求时,我有:

$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'

我的 Session 是一家看起来像这样的工厂:

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

请求没问题。格式化和解析似乎有效。但是,当我 log 时,响应显示为 Resource,而不是 Objectsession.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:

在您的配置阶段或其他初始化逻辑中,添加响应拦截器。

app
    .config(["$httpProvider", function ($httpProvider) {
            $httpProvider.interceptors.push("app.XhrInterceptor");
    });

更多信息

XHR Interceptor in an AngularJS web app

Intercept XHR/Ajax requests with AngularJS http