Failure to trigger success or error callbacks in Angular's $http.get request

Trying to access the nutritionix v1_1 API through a get request has been a bit tricky. Despite the function being called successfully and passing the correct data, the $http.get request seems to be causing some trouble. It simply skips over the remaining code (the .success and .error parts) without returning the promise. I am confident in the request itself, as I have tested it successfully using Postman. The request code looks like this:

(This function is within a factory and is later invoked from a controller.)

let fetchNutrients = (foodId) => {
    let authParams = `appId=${NUTRITIONIXAPIKEY.appId}&appKey=${NUTRITIONIXAPIKEY.appKey}`;
    let filter = 'fields=item_name,item_id,brand_name,brand_id,item_type,nf_calories,nf_total_carbohydrate,nf_dietary_fiber,nf_cholesterol,nf_total_fat,nf_sugars,nf_sodium,nf_protein,images_front_full_url,nf_serving_size_qty,nf_serving_size_unit,nf_servings_per_container';
    
    return (
        $q((resolve,reject) =>{             
            $http.get(`https://api.nutritionix.com/v1_1/item?id=${foodId}&${filter}&${authParams}`)
            .success( (response) => {
                console.log('nutritionix response for nutrients request', response);
                resolve(response);
            }).error(function(errorResponse){
                console.log('nutritionix nutrients request failed', errorResponse);
                reject(errorResponse);
            });
        })
    );
};

And here is how the factory method is called from the controller:

NutrixFactory.fetchNutrients(foodId).then(function(nutrients){
    console.log('returned nutrients', nutrients);
    $scope.nutrients.push(nutrients);
    console.log('array of nutrients', $scope.nutrients);
});

Answer №1

Instead of using success and error, try using try and catch for versions 1.6.*

Deprecation Notice

let fetchNutrients = (foodId) => {
    let authPart =`appId=${NUTRITIONIXAPIKEY.appId}&appKey=${NUTRITIONIXAPIKEY.appKey}`;
    let filter = 'fields=item_name,item_id,brand_name,brand_id,item_type,nf_calories,nf_total_carbohydrate,nf_dietary_fiber,nf_cholesterol,nf_total_fat,nf_sugars,nf_sodium,nf_protein,images_front_full_url,nf_serving_size_qty,nf_serving_size_unit,nf_servings_per_container';
    // let sort = 'sort: {"field":"_score", "order":"desc"}';
    // let typefilter = '"filters":{"not": {"item_type":3}}';
    return (
        $q((resolve,reject) =>{             
           return $http.get(`https://api.nutritionix.com/v1_1/item?id=${foodId}&${filter}&${authPart}`)
            .then( (response) => {
                console.log('nutrix response nutrients request', response);
                resolve(response);
            }).catch(function(errorResponse){
                console.log('nutrix fail nutrients request', errorResponse);
                reject(errorResponse);
            });
        })
    );
};

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

Structuring React components - Incorporating a form within a modal

I am currently utilizing the react-bootstrap Modal, Form, and Button components. My goal is to have the button trigger the modal window containing a form. Once the form is filled out, clicking another button within the modal will validate the data and sen ...

Deactivate a dropdown option in Angular's uib-dropdown

Currently in my angular template, I am working on a dropdown menu using angular-ui. The requirement is to disable certain list items based on a property of the "company" object defined in the ng-repeat. I've already experimented with the disabled tag ...

What steps can I take to mimic a pen-like behavior for my cursor on my sketching website project?

My goal is to create a 16x16 grid with a white background, where each grid item changes color when the mouse is pressed and moved over it, similar to paint. I have written a script to achieve this: let gridContainer = document.getElementById('grid-con ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

AngularJS: Pause the data binding functionality temporarily

How can I temporarily deactivate data binding in AngularJS? I am working with a list called items that is being displayed using ng-repeat. I need to perform some operations on this list without immediately updating the page, as this could cause slowdown. ...

Transforming a JSONP request to automatically parse a text response into JSON

If I have the following request $.ajax({ type: "GET", dataType: "jsonp", jsonp: "callback", jsonpCallback: "my_callback", url: my_https_url, headers:{"Content-Type":"text/html; charset=utf-8"}, success: function(data) { ...

Transforming JSON objects, retrieve an empty value in place of undefined

Can someone please offer some advice on the following: I am retrieving JSON data using this code snippet: $.getJSON(jsonPath, function(returnedData){ ... }); The JSON object returned will have a structure similar to this: ... "skin": { "elapsedTextCo ...

Leveraging promises to make Ajax calls without repeating code

Would it be possible to create an ajax function without duplicating it? Passing different parameters, which are locations to various files. Then utilizing the promise to combine them into a single object, possibly incorporating the spread operator. Is th ...

When trying to run the code locally, JS and Bootstrap seem to have trouble functioning together, despite

Check out my codepen project here: https://codepen.io/ldrumsl/pen/ZxdZwa Below is the JavaScript code: $('#datetimepicker1').datetimepicker(); $('#datetimepicker2').datetimepicker(); Downloaded index.html file content: <!DOCTYPE ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

Calculating and modifying a specific value in my local storage using JavaScript

I've been working on a code that allows me to add, display, and delete objects in local storage. It's functioning fine, but I'm facing an issue when trying to update a specific object. Instead of modifying just the particular object I want, ...

Exploring the realm of styling with React JS

Currently, I am facing an issue while working with material-ui for my web design. Here is the code snippet that I am using: const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(10), direction:"column", alig ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Slider that allows range selection after midday

Currently facing a dilemma using the noUiSlider plugin. I have set up a time range picker starting from 6 am to 6 am the following day. Everything works smoothly until it reaches 23:59, but I need it to display 1:00, 2:00 instead of 25:00, 26:00 for the ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

Utilizing Angular's ng-repeat directive to dynamically generate images, with the added functionality of attempting to

I am utilizing angular-drupal to fetch data from my backend built on Drupal. My objective is to create an image gallery using the default endpoints provided by the services module. I make a call to node load to retrieve a specific node, then I extract the ...

Retrieve the image link from a Flickr JSon Feed

I'm currently displaying images from a flickr feed on my webpage. Everything is working well, but when I click on an image, it takes me to the page where the image is hosted. What I want is for the images to link directly to the image itself, not th ...