AngularJS中$resource设置与获取headers

2016.5.27 - 南京 angularjs

设置

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

app.factory('UserService', function($resource) {
  return $resource('/api/users/:id', {id: '@id'}, {
    get: {
      method: 'GET',
      headers: { 'content-type': 'application/json' }
    }
  });
});

获取

app.controller('UserCtrl', function($scope, UserService) {
  UserService.get({id: 1}, function(data, headersGetter) {
    $scope.users = data;
    var contentType = headersGetter('content-type');
    console.log('content-type:' + contentType);
  });
});

// or
app.factory('UserService', function($resource) {
  return $resource('/api/users/:id', {id: '@id'}, {
    query: {
      method: 'GET',
      isArray: true,
      transformResponse: function(data, headersGetter) {
        var items = angular.fromJson(data);
        var contentType = headersGetter('content-type');
        console.log('content-type:' + contentType);
        return items;
      }
    }
  });
});

更新列表:

*

参考文章:

相关阅读