How to read response headers with $resource?

只谈情不闲聊 提交于 2019-12-21 02:20:35

问题


I'm using $resource to get data from my RESTful service and I need to read response headers to get 'X-Page' and 'X-Total-Pages' value for pagination.

Example:

Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:2637
Content-Type:application/json
Date:Thu, 10 Apr 2014 16:53:01 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
Vary:Origin
X-Page:1
X-Per-Page:10
X-Total:17
X-Total-Pages:2

But I couldn't get full headers from server.

This is returned headers:

This is the headers from server:

This is my code:

.factory('TestAPI', ['$resource',
        function ($resource) {
            return $resource("http://ip.jsontest.com/?callback=showIP", {}, {
                query: {
                    method: 'GET'
                }
            });
        }])

TestAPI.query({}, function (value, responseHeaders) {
                console.log(responseHeaders());
            }, function (response) {
                console.log(response);
 });

回答1:


In your response headers you have to add the following header:

Access-Control-Expose-Headers: X-Total-Pages, X-Page

With this, the browser is capable to expose your customs headers an read it angular.




回答2:


After doing what @nancoder said

You could read the header by adding an interceptor to your $resource.

It would looks like this

.factory('TestAPI', ['$resource',
        function ($resource) {
            return $resource("http://ip.jsontest.com/?callback=showIP", {}, {
                query: {
                    method: 'GET',
                    interceptor: {
                        response: function (resp) {
                            console.log(resp.headers("X-Total-Pages"));
                            console.log(resp.headers("X-Page"));
                            return resp.resource;
                        }
                    }
                }
            });
        }])


来源:https://stackoverflow.com/questions/23000273/how-to-read-response-headers-with-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!