Struggle with Q library in Angular

Currently, I am going through the Angular.js tutorial on pluralsight.com and it has been a smooth experience so far. The tutorials are well-explained and easy to understand. However, I have encountered an issue that I am struggling to resolve on my own. I want my deferred promises to react differently based on whether they succeed or fail, but they always seem to be firing as if they succeeded.

Service:

var resource = $resource('/data/event/:id', {id: '@id'});
return {
    getEvent: function (id) {
        var deferred = $q.defer();
        resource.get({id: id},
            function (event) {
                console.log("This is (EVENT): " + event);
                deferred.resolve(event);
            },
            function (response) {
                console.log("This is (RESPONSE): " + event);
                deferred.reject(response);
            });

        return deferred.promise;

Controller:

 $scope.event = eventData.getEvent(2)
         .then (
              function(event) {
                  $scope.event = event;

                  console.log(event);
              },
              function(response) {
                  console.log(response);
              }
          );

In essence, when I input an incorrect id (to load a non-existing JSON file), I want to be alerted about it.

Answer №1

The $resource service in AngularJS simplifies HTTP requests by adding RESTful conventions to the call made with the $http service. You can find more details about this in the official $resource documentation.

When working with promises returned by $resource, the success callback is triggered if the HTTP status code is 200. If the status code falls within the 400 or 500 range, the error callback is executed, following standard REST practices.

Given that your service consistently returns a 200 Status code, $resource interprets this as a successful server response and triggers the success callback accordingly.

If you need to handle different HTTP status codes, you may want to consider using $http directly or modifying your service to return the appropriate status codes.

I hope this explanation clarifies things 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

Disabling hammer.js touch events with the onclick event

I have recently completed constructing a carousel slider with touch events for a website project. I am currently trying to find a way to deactivate the touch events (hammer) using click events. Below is the code snippet that I have been working on: The cl ...

Searching for nested objects while adhering to JSLint guidelines can be achieved by following

I have a structured object and I'm trying to locate the product using its ID. 0 :{ id: 0, title: 'xxxx', url: "www.test.com" quantity: 100 }, 1 :{ id: 10, title: 'xxxx', url: "www.test.com" ...

Exploring the Concept of Class Inheritance in Javascript

I've been thinking about how to implement Class Inheritance in JavaScript. Since JavaScript doesn't have classes like other languages, we typically use functions to create objects and handle inheritance through Prototype objects. For instance, h ...

Retrieving a single number from Jquery's offset function during scroll events

Seeking the Current Top Position of Web Page Elements In my web page, I have divs with a height of 100%, each containing different content. I am attempting to determine the top position of these divs to manipulate them accordingly. However, when I try to ...

Utilizing the map() function to iterate through a list of outcomes and assigning the resulting array as the state of a component in ReactJS

Currently, I am facing an issue with assigning an array value to the state in my react project. In order to do this, I have initialized my state as follows: constructor(props) { super(props); this.state = { category: [] } } My objec ...

What is the proper way to document JSDoc in JavaScript specifically for the TypeScript Compiler?

There is a feature that allows you to check JS code with the TS compiler. The TS compiler also recognizes JSDoc comments (https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript). I am looking to utilize the TS compiler in my React projec ...

Utilizing the ng-init directive to initialize code based on a JSON object

I am attempting to connect the value of ng-init to an input from a JSON object. However, I am receiving a "Syntax Error: Token" message. Can someone help me identify where I am making a mistake? $scope.obj = { init: 'obj.value = obj.value || 20&apos ...

How can I prevent vuejs watch methods from being triggered when the value is modified by the same method?

monitorChanges: { observeValue() { setTimeout(() => { this.observeValue = ""; }, 4000); } } In this scenario, the observeValue function is initially invoked by the DOM, but it repeats when the value ...

Storing a portion of AJAX response as a PHP variable

Is there a way to store data received through an AJAX response in a PHP variable? I want to take the value of $('#attempts_taken').val(data[11]); and save it as a PHP variable. Any help would be great! <script type="text/javascript> $(do ...

React.js: Passing an array as a property to an element results in the transformation of the array into an object

I'm trying to understand why passing an array as a prop to another element results in it getting transformed into an object with the array as its value. I need help understanding if this is a common JavaScript 'quirk' or specific to React an ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

Tips for extracting function data and storing it within scope after resolving a route in AngularJS

Is there a way to fetch data from a function and store it in the scope using resolve in an AngularJS route? For instance: .state('list.employee_list', { url: "/employee_list", templateUrl: "views/list/employee_list.html" ...

Extracting a single string from a JSON object: A step-by-step guide

Currently, I am working on retrieving a JSON document from my MongoDB. Once fetched, my goal is to extract only the "email" field so that I can utilize it for sending emails to users. setInterval(()=>{ return User.find({email: &apos ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Instructions for concealing a parent div and substituting it with a different div upon the user's click on a button nested within the parent div

I am working on a component that consists of two buttons. The goal is to hide the entire component when one of the buttons is clicked and replace it with another component. Although I have successfully hidden the clicked button, I am struggling to hide th ...

Using Jquery to dynamically add or remove a class based on scrolling behavior

Can someone help me with identifying the position of an element so that when the user scrolls to it and it appears on the screen, an icon can be highlighted? Currently, the script I am using adds the class too early, closer to the bottom of the block. I w ...

Eliminating property while saving data to JSON file

I have retrieved data from an API in JSON format, saved it to a JSON file on a web server, and now I am displaying specific content from that file on a webpage using Angular.js. The NodeJS code I am using to save the API response to a file is as follows: ...

Can someone show me how to create a JavaScript countdown with a Unix timestamp?

I'm in the process of building a website that requires a countdown to a specific time, but I'm struggling to find a solution that allows me to input a Unix timestamp and display the same countdown for all users, irrespective of their time zones. ...

Tips for preparing your response for delivery in Nest.js?

After carefully following the documentation, I successfully implemented an interceptor for response mapping. I am aiming to establish a uniform JSON format for all responses. Is there a more effective way to achieve this rather than using an interceptor? ...

Minimize and dismantle the object deconstruction/allocation

Imagine I have two basic objects and I want to combine their properties to create a third object. It works smoothly with this code: (()=>{ const firstObj = {a: 2, b: 3} const secondObj = {a: 100, c: 5} return {...firstObj, ...secondObj} })() // { ...