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

Switching CommonJS modules to an ESM syntax for better compatibility

I'm currently facing a challenge in grasping the process of importing CommonJS modules into an ESM syntax. Specifically, I am working with the library url-metadata. This library provides a top-level export as a callable function, which deviates from t ...

Simple request results in an error

I have been experimenting with the Electrolyte dependency injection library, but I am encountering an error even when trying a simple script that requires it. I haven't come across any discussions or problems similar to mine in relation to this issue ...

What is the best way to create a global variable using jQuery?

Is it possible to pass the value of a_href = $(this).attr('href'); function globally and set a_href as "home"? var a_href; $('click a').on('hover', function(e){ a_href = $(this).attr('href'); ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

What is the best way to transform a JavaScript file retrieved from a remote server (returned as a string) into a standard JavaScript object in a Node

Is there a way to convert a JavaScript file fetched from a remote server (which is in string format) into a regular JavaScript object in Node.js? I know that I can use JSON.parse to convert a JSON string into a dictionary, but in this case, the file contai ...

What is the solution to the error "modal is not defined" in Vue.js?

Hey guys, I need some help with an error that popped up: [Vue warn]: Error in v-on handler: "TypeError: $(...).modal is not a function". The issue is with the modal function Below is the code snippet from my welcome.blade.php: <body> &l ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

Incorrect Results from Angular Code Coverage

Currently using Angular.js, Karma, Karma-coverage (Istanbul), and Jasmine for my stack. While conducting Code Coverage analysis on my app, I encountered an issue which leads to my question - Service A is showing up as covered by tests (in green) even thou ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Sails encountering CORS preflight error due to cross-origin request

I am new to creating hybrid apps and have been following some tutorials. However, I encountered these errors on my browser console: Refused to load the script 'http://192.168.1.142:35729/livereload.js?snipver=1' due to Content Security Policy di ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles. For instance, when a client logs in, I retrie ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Delayed Passport Session Login

Every time I try to log in, my Express app loads very slowly... I've implemented Passport and Express Validator, but there are no errors. However, the login process for some users is extremely slow. Can anyone offer assistance? Below is a snippet o ...

The `forEach` method cannot be called on an undefined node.js

I have been developing a small study website but encountered an issue with the title. Despite extensive internet research, I have not been able to find a solution. The system I am using is Ubuntu with node.js, express, and mysql. app.js var fs = requir ...

Preventing an event from bubbling up to its parent in a jQuery Ajax call: A step-by-step guide

I am working on a page that showcases a tree list using unordered lists. Each li element with children triggers an ajax call to fetch those children and display them as another ul/li combination, which is functioning correctly. However, the problem arise ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

Using Firebase Realtime Database, this React dropdown menu is populated with options in real-time. Combining the features

I'm currently facing an issue with a dropdown that is supposed to loop through data fetched from the Firebase realtime database. The goal is to assign a selected value to a Formik form for saving it to another object in the database. In my database, ...