Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block.

For example, if I have a simple call like this:

$http.get('/users')
  .then(function(res) {
    return res.data;
  }, function(err) {
    console.log(err);
  });

If I encounter a 500 Internal Server Error, it ends up in the onSuccess block. It seems strange to me because technically I did receive a response? My understanding of promises tells me that this is correct, but having error handling logic in an onSuccess block doesn't feel right.

if(res.status >= 400) {
  return $q.reject('something went wrong: ' + res.status);
}

Should I handle 400+ status codes in the onSuccess block or should I return a rejected promise to ensure the onReject block is executed? Is there a better way to handle this situation that I am missing?

I attempted to handle this in an httpInterceptor, but I was unable to figure out how to return a rejected promise from there.

this.responseError = function(res) {
  if(res.status >= 400) {
    // do something
  }

  return res;
};

Answer №1

Ensure your success block is functioning properly. Test the code and verify that the error block will execute if the error code is greater than 300.

$http.get('/users').success(function(data, status, headers, config) {
    // This function will be executed asynchronously
    // when the response is received
  }).error(function(data, status, headers, config) {
    // This function will be executed asynchronously in case of an error
    // or when the server responds with an error status
  });

Answer №2

One way to approach this issue is by utilizing an interceptor instead of relying solely on your callback function.

To implement this, you can update your $httpProvider configuration in the app.config section with code similar to the following:

$httpProvider.interceptors.push(['$q', function ($q) {
    return {
        request: function (config) {
            //perform necessary actions
            return config;
        },
        responseError: function (response) {
            if (response.status === 401) {
                //handle unauthorized access
            }
            return $q.reject(response);
        }
    };
}]);

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

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" Attempting to achieve this ...

Manipulate and transform elements within an array using both Filter and Map functionalities in React

Below is the component I am working with: function Params(props) { const { Parameters } = useFetchParams(); return ( <div className='Params'> { Parameters && Parameters.map(parameter =&g ...

Developing a Prototype for an Angular Directive

After following instructions from a question on Stack Overflow, I have updated my application configuration with the code snippet below: $provide.decorator('formDirective', function($delegate) { var directive = $delegate[0]; directive.contro ...

Node.js can be utilized to make multiple API requests simultaneously

I am facing an issue while trying to make multiple external API calls within a for loop. Only one iteration from the for loop is sending back a response. It seems that handling multi-API requests this way is not ideal. Can you suggest a better approach fo ...

Obtaining a date and time in PHP from a JavaScript array

I am currently working on implementing a JQuery datetime picker and my goal is to save the selected date and time into a PHP variable for storage in a MySQL database. Despite browsing through various examples, none of them seem to be effective in achieving ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Leveraging $sceDelegateProvider for allowing Youtube in Typescript

I'm currently facing an issue with my app where I am trying to enable users to input Youtube URLs for videos to be displayed on the site. However, before implementing this feature, I need to whitelist Youtube. How can I adjust my typescript file (app. ...

Is it possible to customize the color of the modal backdrop in layer v4 of the Material-UI library

I am struggling to modify the background color of an MUI V4 modal. Instead of getting a clean color, I am seeing a gray layer on top of the backdrop. Though this seems to be the default behavior, I want to remove it and target the shaded div directly rathe ...

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Enhance the input by incorporating more fields without altering the existing content

Currently, I am working on creating an input form that includes multiple fields and has the capability to generate a preview of the entered content in a separate div. One key feature I would like to implement is allowing users to add additional fields as n ...

Can someone please point out where this JSON member is defined?

This excerpt from the angular.org website showcases some code: angular.copy <div ng-controller="Controller"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="emai ...

How to change numbers into words using AngularJS

Could someone assist me with converting numbers into words using AngularJS? For instance, if the amount I receive from a service is 9876, I would like it displayed as "Nine Thousand Eight Hundred and Seventy Six" in a table. Please provide guidance on how ...

Exporting a node express app for chai-http can be done by creating a module

I have set up an express app with multiple endpoints and am currently using mocha, chai, and chai-http for testing. Everything was running smoothly until I added logic for a pooled mongo connection and started creating endpoints that rely on a DB connectio ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element: <div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <! ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Having trouble getting my ReactJS page to load properly

I am currently linked to my server using the command npm install -g http-server in my terminal, and everything seems to be working smoothly. I just want to confirm if my h1 tag is functional so that I can proceed with creating a practice website. I have a ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...