在 AngularJS 中的 $http 调用中访问 header 的属性

Access header's properties within a $http call in AngularJS

根据 github API 的分页文档,我正在尝试请求事件项并检索 Link header (just like they suggest)建立分页。问题是我不知道如何处理 headers('Link') object.

函数:

getEvents: function(page) {        
        if(cacheService.get('eventos_'+page)) {
          return cacheService.get('eventos_'+page);
        } else {
          var deferred = $q.defer();
          $http.get('https://api.github.com/repos/'+owner+'/'+repo+'/events', {params: {per_page: 15, page: page}})
          .success(function(events, status, headers) {
            console.log(events, status, headers('Link'));
               cacheService.put('eventos_'+page, events);
            deferred.resolve(events);
          }).error(function(err) {
            deferred.reject('Error', err);
          });
          return deferred.promise;
        }
      }

结果“object”(如果可以这样调用的话)是:

"
<https://api.github.com/repositories/XXXXXX/events?page=2&per_page=15>; rel="next",
<https://api.github.com/repositories/XXXXXX/events?page=4&per_page=15>; rel="last"
"

¿如何在 $scope 变量中保存页码(下一页和最后一页)?或者至少我怎样才能遍历 object? 别笑,我试了headers('Link').rel['last']当然没成功。

来自 angular$http 文档 https://docs.angularjs.org/api/ng/service/$http 响应 object 具有以下属性:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

并从 header 的 headers['Link'] 中获取数据,如果您可以在回复中看到 'Link' header

下面是从 header 获取分页链接的代码,如果您发送分页参数作为响应 header

function parseHeader(header){
 // Split parts by comma
        var parts = header.split(',');
        var links = {};
        // Parse each part into a named link
        angular.forEach(parts, function (p) {
            var section = p.split(';');
            if (section.length != 2) {
                throw new Error("section could not be split on ';'");
            }
            var url = section[0].replace(/<(.*)>/, '').trim();
            var queryString = {};
            url.replace(
                new RegExp("([^?=&]+)(=([^&]*))?", "g"),
                function([=11=], , , ) { queryString[] = ; }
            );
            var page = queryString['page'];
            if( angular.isString(page) ) {
                page = parseInt(page);
            }
            var name = section[1].replace(/rel="(.*)"/, '').trim();
            links[name] = page;
        });

        return links;
}