AngularJS Resource GET Request Unsuccessful

Is there a way to verify if a resource failed to be fetched in AngularJS?

For instance:

//this is valid syntax
$scope.word = Word.get({ id : $routeParams.id },function() {
    //this is valid, but won't be triggered if the HTTP response is 404 or any other http-error code
});

//this is something similar to what I want 
//(PLEASE NOTE THAT THIS IS INVALID AND DOES NOT EXIST)
$scope.word = Word.get({ id : $routeParams.id },{
    success : function() {
      //success
    },
    failure : function() {
      //404 or error
    }
});

Any thoughts on how to achieve this?

Answer №1

If an error occurs, a second callback function will be triggered following the initial callback function. This snippet is sourced from the official documentation and a discussion on a Google forum post:

$scope.word = Word.get({ id : $routeParams.id }, function() {
    //good code
}, function(response) {
    //404 or bad
    if(response.status === 404) {
    }
});
  • To perform HTTP GET "class" actions: Resource.action([parameters], [success], [error])
  • For non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
  • Non-GET instance actions are handled as follows: instance.$action([parameters], [success], [error])

Answer №2

In response to @Adio's query, let me clarify.

The second callback function is triggered in AngularJS when any HTTP response code falls outside the range of [200, 300], which are considered successful codes. This allows for a unified error handling approach without needing to specify individual errors. While an if statement can be utilized to perform specific actions based on the error code, it is not a requirement.

Answer №3

This message serves as a notification.

Starting from angular 1.6.x, the use of success and failure is no longer supported. It is advised to now utilize the then and catch methods instead of success and failure.

Therefore, when working with angular 1.6.x, the code should be written as shown below:

$scope.word = Word.get({ id : $routeParams.id }).then(=> () {
    // This code block is valid, but will not execute in case of an HTTP response error such as 404 or any other http-error code
}).catch(=> () {
    // Insert error handling code here
});

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

Issue with extraction from JSON data

I am currently working with a JSON data example that looks like this: Array ( [data] => Array ( [0] => Array ( [name] => Jonathan James[id] => 45879) [1] => Array ( [name] => Jackson C. Gomez [id] => 989) [2] => Array ( [name] => ...

The index.js file in ReactJs is failing to run completely

A couple of months back, I delved into the world of React but eventually put it on hold. Today, I decided to pick it back up and took the following steps: npm init npm install npm start Everything seemed to run smoothly (No Errors), but strangely nothing ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Leveraging a JavaScript variable declared outside the function to successfully transfer data to my AJAX function

Every time the enter key is pressed, my AJAX function gets executed. I used to pass a set of javascript variables equal to elements in the HTML (the contents of a text area) as data for the AJAX function. Now, I want these JS variables to hold values from ...

Finding it difficult to grasp the concept of enabling CORS through an ajax request

I'm struggling to figure out how to enable CORS while using Ajax to send data to a remote server on a different domain. Despite researching extensively and reading numerous Stackoverflow threads, I can't seem to make sense of it all. I understand ...

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

initialize input data in vue

How can I set a default value for an input in a date picker using Vue JS? I have tried setting the data but it's not showing up. When I inspect the element, I see this code: https://i.stack.imgur.com/fQDLL.png Here is my script: new Vue({ e ...

How can I access data from a function that is executed within a method in Vue.js?

When working with vuejs and JS scopes, passing a value to a style property inside data can be tricky. The issue arises when trying to access this.data.property: Vue.component ('loader-component', { template: '#loader-template', mo ...

The combination of HighCharts and CodeIgniter failed to produce any results when attempting to display data

I was attempting to showcase data from a database table using a bar chart. I opted to utilize the HighCharts library for this purpose. Initially, the chart loaded with default template data, but after making some modifications to display data from the data ...

Use Javascript to extract an array of strings enclosed in double quotes

Is there a way to extract an array containing ["13139","13141", "13140"] from the following data structure? { "13139": [tx[0]], "13141": [tx[1]], "13140": [tx[2]] } I attempted to use JS ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Encountering a glitch while attempting to render with the select tag in React.js

I have developed two functions that generate JSX content and created a logic to display each function based on the user's choice: const Register = () =>{ const [value, setMyValue] = useState() function Zeff(){ return( <div> <h1& ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...

Exploring the World of Html

I'm struggling with an HTML problem related to a web programming class I'm taking. The assignment involves creating a video game using HTML and JavaScript, where an image moves randomly on the screen and the player must click on it as many times ...

submitting a form including a file through ajax communication

For the past two weeks, I've been trying to find a solution to my unique problem. I've created a custom form that I need to upload along with one or more files. Our backend is running ruby on Rails, and the data must be formatted into a specific ...

Issue with Flat-UI: Navigation bar is not collapsing correctly. Need help to resolve this problem

I am currently utilizing the most recent Twitter Bootstrap along with Flat UI. I have been trying to create a basic navbar that collapses when the screen size is reduced. How can I resolve this issue? This is how it currently appears: My navigation items ...

Is there a way to always keep an element positioned directly above a fluid image that is perfectly centered?

My current project involves creating an overlay to display a fluid image of any size. The challenge I'm facing is how to consistently position the close button 30px above the image and flush with its right edge. The catch is that the container doesn&a ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...