Using AngularJS to access the properties of a header within a $http request

As I navigate through the github API's pagination documentation, I am attempting to retrieve event items and extract the Link header (as recommended) in order to construct the pagination. However, I am facing difficulty in understanding how to work with the headers('Link') object.

Function:

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;
        }
      }

The resulting data structure (if it can be described as such) is:

"
<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"
"

How can I store the page numbers of 'next' and 'last' in $scope variables? Alternatively, how can I traverse this object? I attempted using headers('Link').rel['last'] without success, unfortunately.

Answer №1

According to the information provided in the $http document of Angular, here are the properties of the response 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.

If you need to retrieve data from headers, you can use headers['Link'] as long as 'Link' is present in your response header.

Below is a sample code snippet to extract pagination links from the header if you are including pagination parameters in the response 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(/<(.*)>/, '$1').trim();
            var queryString = {};
            url.replace(
                new RegExp("([^?=&]+)(=([^&]*))?", "g"),
                function($0, $1, $2, $3) { queryString[$1] = $3; }
            );
            var page = queryString['page'];
            if( angular.isString(page) ) {
                page = parseInt(page);
            }
            var name = section[1].replace(/rel="(.*)"/, '$1').trim();
            links[name] = page;
        });

        return links;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to connect JQuery to a different page through a data attribute connection

I am currently working on a slider that connects slides from an external page through data attributes. Here is the setup: Main Page <div id="sitewrapper"> <section class="sliderwrapper"> <div id="slider" data-source="slides-pa ...

Difficulty in accessing controller data in AngularJS with ng-repeat

I am trying to display comments using ng-repeat in a section, but I am having trouble accessing the data. Even after debugging, I cannot access the data without modifying the controller. I am new to Angular and prone to making mistakes. HTML / JS &apo ...

Validating the existence of a file through HTTPS in Javascript

After attempting to retrieve the file using this code, I've encountered an issue - it works with HTTP requests but not HTTPS requests (which is what I require). function checkUrl(url) { var request = new XMLHttpRequest(); try { request.ope ...

Using prerender.io in conjunction with native Node.js

Currently, I am working on integrating prerender.io into my Angular 1.6.0 application that is being hosted on a Node.js server. The instructions provided in the documentation for setting up the middleware involve using the connect middleware, with a speci ...

The function .click() fails to execute upon page load, yet it functions successfully when utilized in the console

This is the code I am using: <script> document.getElementById("test").click(); </script> When I try to trigger the click(); function on page load, it doesn't work. However, when I execute it in the console on Firefox, it works ...

Is there a way to route an angular request through a spring filter prior to validation?

I'm currently working on implementing an XSS Filter in a backend application (built with JAVA and Spring). The goal is to validate input values from a frontend app (AngularJS) against the filter before proceeding to validate the rest of the content. ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

Eliminate negative values in CSS using jQuery

In my AngularJS project, I am utilizing jqLite for some custom CSS properties implementation. Here is an example of how I am incorporating the custom CSS properties: $scope.$on('scrollEvent', function(){ if (a < 5){ a = a + 1/2 ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

Insert a CSS Class into an HTML div element with JQuery

I'm faced with a bit of a challenge. Here's the scenario: <div class="portItem"></div> <div class="portItem"></div> <div class="portItem"></div> <div class="p ...

Issues with integrating chart.js in Laravel 7: Element #app not found?

Currently, I am utilizing chart.js to display the statistics of reviews and messages for a user. However, I have encountered issues with the scripts. While the stats are functioning correctly, an error message stating Cannot find element: #app is appearing ...

How can I make sure to consider the scrollbar when using viewport width units?

I've been working on developing a carousel similar to Netflix, but I'm facing an issue with responsiveness. I've been using a codepen example as a reference: Check out the example here The problem lies in the hardcoded width and height use ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Utilizing dynamic class and color binding features in VueJs?

I need help with implementing a Custom Sort method on my divs to arrange them in ascending or descending order. My query is how can I pre-set the icon color to grey by default, and only change it to black when clicked, while keeping the others greyed out a ...

Tips for accessing the initial value within JSON curly braces

In my code, there is a function that returns the following: { 'random_string': '' } The value of random_string is an unknown id until it is returned. How can I extract this value in JavaScript? Appreciate any help. Thanks. ...

Selecting an option in Angular will only send the value ID

I am attempting to utilize ngOptions in Angular. My goal is to pass a parameter to the back-end that sends only the value, not the entire object. Below is my code: <div class="form-group"> <label>Parent Menu</label> <select class ...

Using Node.js to serialize JSON POST data as an array

Looking to retrieve POST data from my front-end form. Upon using console.log(req.body), I receive the following output: [ { name: 'name', value: 'kevin' } { name: 'email', value: '' }, { name: 'phone' ...

There seems to be an issue with the functionality of the JavaScript Quiz as it is

While working on my JS quiz, I encountered an issue where some answers were not displaying due to quotes and the need to escape HTML characters. Additionally, I am facing difficulty in accurately awarding points or deductions based on user responses. Curre ...