How to extract metadata from a transformed response using Angular's $resource

Here is the API structure I am working with:

{
"meta": {
    "total_item": 1,
    "number_of_pages": 1,
    "page_number": 1,
    "status": "Success"
},
"data": [
    {
        "name": "Operator 1",
        "short_name": "OP1",
        "_id": "534d69bba758b3b7839ba7b9",
        "__v": 0,
        "users": [
            "532ef6e28b42970ab797444f"
        ]
    }
]
}

In my Angular application, I am using $resource to interact with this API. Here is a snippet of the code:

var apiDataTransformer = function ($http) {
  return $http.defaults.transformResponse.concat([
    function (data, headersGetter) {
      var result = data.data;
      result.meta = data.meta;
      console.log(result);
      return result;
    }
  ])
};

angular.module('ua.common').factory('uaApi', function($resource, $http){
  var factory = {};
  factory.operator_ressource = $resource(
    '/operators/:operatorId',
    {},
    {'query': {method: 'GET', isArray: true, transformResponse: apiDataTransformer($http)       } }
  );
  return factory;
})

When I query these resources and check the response in the console, some unexpected behavior occurs. The meta object gets lost in the process even though I used transformResponse to retain all data.

Is there a way to preserve the meta object while using $resource in Angular for pagination purposes?

Answer №1

To enhance your sideband paging data and an array of resource objects from the query method, you can create a custom factory function in transformResponse.

Consider utilizing the following code snippet:

angular.module('ua.common').factory('uaApi', function($resource, $http){
    var factory = {};
    factory.operator_ressource = $resource('/operators/:operatorId', {},
        {'query':
            { method: 'GET',
              isArray: false,
              transformResponse: function(jsondata){
                  return { meta : jsondata.meta,
                           results : jsondata.map(function(result){
                                return new factory.operator_ressource(result);
                              })
                         }
              }
            }
         }
    );
    return factory;
});

This technique has proven effective for me; I typically instantiate a pager object and combine it with an array of $resource objects.

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

Smooth scrolling feature for Wordpress websites

I am currently in the process of converting an HTML5 template into a Wordpress theme. One specific feature I'd like to add is a custom scroll for Wordpress using the code: <script src="jquery.nicescroll.js"></script> DEPENDENCIES This cod ...

Unraveling unicode escape sequences in JavaScript strings

My code includes a string like \uC88B\uC544\uC694. When I use this string in a node repl (v7.4.0), it displays '좋아요' correctly. However, when I try to use the same string in the following code snippet, it does not work as ex ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

The web API PUT method is able to process query strings, however it is not properly

When I use users as a query string parameter and set the web API method to look for them in the URI, everything works fine. However, when I pass them in as shown below, the users variable ends up being null. What could be causing this issue? Angular funct ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

Conceal overflow in SVG after stroke is applied to top rectangle border

Is there a way to conceal the overflowing red color in this SVG? I attempted repositioning it before the rect with the stroke, but that didn't solve the issue. Check out the code and screenshot below. <br><br> <svg _ngcontent-fdl-c1 ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

Adding ngSanitize as a dependency causes the app to malfunction

Whenever I integrate ngSanitize into my Angular application, it seems to disrupt the system's functionality. Here is the setup for adding ngSanitize: angular.module('routings', ['ngSanitize']).controller('RoutingsController& ...

`json_encode does not output a UTF-8 character`

I send an AJAX request to the PHP server, and receive back an array encoded in JSON. This array has only two indexes. When I log it using console.log(), this is what I see: {"1":"\u00d9\u0081\u00db\u008c\u00d9\u0084\u0 ...

What techniques can be employed to create a fully operational web application using AngularJS?

I have taken on the challenge of understanding AngularJS by creating a webapp. Within my Eclipse environment, I am working with 4 files: main.js, index.html, view1.js, and view2.html. Currently, I can get index.html to load when Tomcat is running. Embedd ...

Function was expected to call toggleStyle spy, but it did not

Currently, I am implementing Jasmine testing for my project. Below is the function that I am working with: style: string; toggleStyle(style: string, version: string) { this.style = `mapbox://styles/mapbox/${style}-${version}`; } Accompanied by th ...

Transferring data between components in React by passing parameters through Links

When calling another component like <A x={y}/>, we can then access props.x inside component A. However, in the case of calling EditCertificate, the id needs to be passed to the component. I am using a Link here and struggling to pass the id successf ...

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

What is the best way to display two radio buttons side by side in HTML?

Looking at my HTML form in this JSFiddle link, you'll see that when the PROCESS button is clicked, a form with two radio buttons appears. Currently, they are displayed vertically, with the female radio button appearing below the male radio button. I& ...

Deciphering JavaScript script within a Node.js module

// =============================================================================== // Auth // =============================================================================== const admin = require('firebase-admin'); //what happens if i move th ...