What could be causing the $httpProvider.interceptors to unexpectedly return an 'undefined' value?

Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors.

This is the structure of my app:

var app = angular.module("restaurantList", []);

The yelpAPI service handles authentication and generates an HTTP request. The received data is output to the Web Console as follows:

app.controller("mainCtrl", ["$scope", "yelpAPI", function ($scope, yelpAPI) {
    $scope.restaurants = [];
    yelpAPI.get(function (data) {
        $scope.restaurant = data;

        console.log($scope.restaurant);

    });

}]);

The data from the request looks like this:

Object {region: Object, total: 37, businesses: Array[20]}

I aim to parse the array nested in the businesses property. My approach was to utilize $httpProvider.interceptors for this purpose.

The initial configuration of $httpProvider.interceptors:

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push(function () {
        return {
            response: function (response) {

                return response;
            }
        }
    });
});

The updated version of $httpProvider.interceptors:

app.config(function($httpProvider) {
    $httpProvider.interceptors.push(function() {
        return {
            response: function(response) {

                var old_response = response.businesses,
                    new_response = [];


                for (var i = 0; i < old_response.length; i++) {

                    var obj = old_response[i],

                        new_obj = {
                            restaurant_name: obj.name,
                            phone_number: obj.display_phone,
                            yelp_rating: obj.rating,
                            reservation_url: obj.reservation_url
                        };

                    new_response.push(new_obj);
                }

                return new_response;
            }
        }
    });
});

An error is now showing up -

TypeError: Cannot read property 'businesses' of undefined
. Any suggestions on what I might be missing?

EDIT #1

After printing the response using console.log(response), I realized that response.businesses should actually be response.data.businesses. This fixed the error, but now my $http call is returning undefined. Do you have any insights on what could be causing this issue?

EDIT #2

app.factory("yelpAPI", function($http, nounce) {
    return {
        get: function(callback) {
            var method = "GET",
                url = "http://api.yelp.com/v2/search";
            var params = {
                callback: "angular.callbacks._0",
                oauth_consumer_key: "my_oauth_consumer_key",
                oauth_token: "my_oauth_token",
                oauth_signature_method: "HMAC-SHA1",
                oauth_timestamp: new Date().getTime(),
                oauth_nonce: nounce.generate(),
                term: "American",
                sort: 2,
                limit: 20,
                radius_filter: 4000,
                deals_filter: true,
                actionlinks: true
            };
            var consumerSecret = "my_consumer_secret",
                tokenSecret = "my_token_secret",
                signature = oauthSignature.generate(method, url, params, consumerSecret, tokenSecret, {
                    encodeSignature: false
                });
            params["oauth_signature"] = signature;
            $http.jsonp(url, {
                params: params
            }).success(callback);
        }
    }
});

Answer №1

When using Angular, the following code snippet will handle responses from $http requests and modify them accordingly:

app.config(function($httpProvider) {
    $httpProvider.interceptors.push(function() {
        return {
            response: function(res) {

                var old_response = res.businesses,
                    new_response = [];


                for (var i = 0; i < old_response.length; i++) {

                    var obj = old_response[i],

                        new_obj = {
                            restaurant_name: obj.name,
                            phone_number: obj.display_phone,
                            yelp_rating: obj.rating,
                            reservation_url: obj.reservation_url
                        };

                    new_response.push(new_obj);
                }

                return {data : new_response};
            }
        }
    });
});

The modified response object will now be returned as {data : new_response}

Answer №2

Thanks to Emir, the problem was resolved. It turns out that when you utilize $httpProvider.interceptors, it is necessary to modify the response.data and return the complete response object, rather than just a new array like I initially attempted. This is because $http automatically selects the data property for you.

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

What is the best method for integrating data retrieved from an API using Python into a frontend framework?

I'm new to coding and could use some guidance. I've managed to retrieve data from an API in JSON format by running my Python script. Now, I want to display this data on a separate front-end framework with the click of a button. Essentially, one b ...

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

Fixed width for the last column in DataTables

Here's the scenario: I have a jQuery script that loads DataTables, and I know how to set the "aoColumns" : "sWidth" parameter to fix the width of a specific column, which is working fine. However, my issue arises from having multiple tables with var ...

The JavaScript code is producing a numerical output instead of the intended array

I am facing an issue with my program that is designed to eliminate items from a list of arguments. function destroyer(arr) { var args = [].slice.call(arr); var data = args.shift(); for(var i = 0; i < args.length; i++){ var j = 0; while(j ...

Angular 2 - Graphic Representation Tool for Visualizing Workflows and Processes - Resource Center

Looking for a library that can meet specific requirements related to diagram creation and rendering. We have explored jsplumbtoolkit, mermaid, and gojs, but none of these fully satisfy our needs. For example, we need the ability to dynamically change con ...

Troubles with Vue and localStorage for storing a theme's data

I've been struggling with this issue for a while now while working on a Vue site. I have not been able to find a solution for my specific bug in other discussions. The concept should be straightforward - I want to have a switch that toggles a value b ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

What is the process for renaming a Discord channel through nodeJS and discordJS?

I'm currently developing my first Discord bot using node.js and discord.js. My objective is to provide real-time information about a Minecraft server through Discord. What I aim to achieve is to have a channel that automatically updates its name per ...

Steps for adding a delete icon to a text input field and enabling the functionality to delete text

In the code snippet below, I am creating a text input field: <input type="text" class="signup-input text-value" name="" placeholder="e.g. <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d48554c405d41486d">[email pro ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

Unable to transform into a tangible entity

When I run the code below, I encountered an error stating: Uncaught exception: TypeError: Cannot convert 'validation.messages.field' to object $.fn.validate = function(validation) { $.each(validation.rules, function(field, fieldRules){ ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Transitioning from one bootstrap modal to another in quick succession may lead to unexpected scrolling problems

I'm facing a challenge with two modals where scrolling behavior becomes problematic when transitioning from one to the other. Instead of scrolling within the modal itself, the content behind it is scrolled instead. In order to address this issue, I im ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

``Changing the value of the radio button does not update the ng-model variable

I have encountered an issue with my code. Upon page load, the radio button is checked but the ng-model value session.payment does not get updated automatically. I have to manually select it again for the update to take effect. <li ng-repeat="method i ...

Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code. For example: <div id="result" class="card"> <img src="hello.png" ...

When using NodeJS with expressJS, remember that req.body can only retrieve one variable at a

I'm having trouble with my login and signup pages. The login page is working correctly, but the signup page is only transferring the password for some reason. App.JS: var express = require("express"); var app = express(); var bodyParser = require("bo ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...