Utilizing the .always().error() syntax to handle errors in Angular $q promises

I am creating a simplified wrapper around $http for our REST API, aiming to return a promise in a similar fashion as $http does (after data manipulation).

Here is the service I have set up:

Services.service('Item', ['$http', '$q', function($http, $q){
    var deferred = $q.defer();
    var getSuccess = function(data, status, headers, config){
        var item = angular.copy(data);
        item.primaryImage = 'https://my.cdn.com/' + item.meta.images[0].s3id;

        if(item.meta.source_link !== null) {
            item.sourceLink = item.meta.source_link.url;
        }

        deferred.resolve(item, data, status, headers, config);
    };
    var getError = function(data, status, headers, config) {
        deferred.reject(data, status, headers, config);
    };

    this.get = function(userID, itemID) {
        $http({
            method: 'GET',
            url: '/api/items/' + userID + '/' + itemID
        }).success(getSuccess).error(getError);

        return deferred.promise;
    };
}]);

However, based on my understanding of the documentation, it seems that I need to utilize .then(success, error, always) instead of .success().error().always() like how $http works.

Is there a way to implement promises in a similar manner to $http? That would be very convenient.

var req = Item.get($routeParams.userID, $routeParams.itemID);

req.success(function(item){
        window.console.log('Received item:', item);
    });
    .error(function(item){
        window.console.log('Oops. It failed.')
    })

Answer №1

After delving into this question, I took some time to search for solutions that would fulfill your requirements.

A demonstration of how I tackled the issue can be found in this Plnkr: http://plnkr.co/edit/LoCuwk26MEZXsugL1Ki5

The crucial part is highlighted below:

var promise = defered.promise;

  promise.success = function(fn) {
    promise.then(function(res) {
      fn(res);
    });
    return promise;
  };

  promise.error = function(fn) {
    promise.then(null, function(err) {
      fn(err);
    });
    return promise;
  };


  return promise

This snippet is extracted directly from the angular source code, indicating it as an optimal approach for replicating such a style.

An error caught my eye in your implementation. It's worth noting that all services are singletons, implying that only one deferred object should be created. Consider creating one on each call and utilizing it accordingly.

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

What is the process for initiating printing in a separate window?

Is there a way to modify the code below so that when I click "Print" it opens in a new window instead of redirecting and losing the original receipt? <div class="print_img"> <button onclick="myFunction()"> <div align="justify ...

The scrolling speed of Ionic Load More feature is a bit sluggish

Hey there! I'm a newcomer to Ionic and AngularJS. In my current project with Ionic v1, the load more scrolling feature is extremely sluggish. I've attempted two different methods: Using a Service Using a Factory Both approaches are proving t ...

Source for JSON autocomplete

After extensive testing and tweaking, I am exploring different options for sourcing search suggestions to index in Elasticsearch using crawled data from Nutch. I have found varying results and am wondering if there is a more effective approach available. ...

AngularJS: Component fails to load controller

I am managing a directory structure that looks like this --- js/app.js ------- components ----------- header -------------- headerComponent.html -------------- headerComponent.js -------------- headerController.js Within index.html, I have the following ...

Encountering NaN in the DOM while attempting to interpolate values from an array using ngFor

I am working with Angular 2 and TypeScript, but I am encountering NaN in the option tag. In my app.component.ts file: export class AppComponent { rooms = { type: [ 'Study room', 'Hall', 'Sports hall', ...

Resetting the positions of images can be done by following these

I'm currently in the process of developing a game and need assistance with implementing a game end function. Can you provide guidance on how to reset all images back to their original positions? ...

Is it possible to declare variables within a React 'render' function?

I have data arranged in multiple columns on several rows, with a react element corresponding to each data element. The number of elements on the first row can vary between 4 and 6. For instance, I may display a user's name, birthday, and email. If t ...

Error in Ionic app: Controller malfunctions when push logic is embedded within it

Current Dilemma: Currently, I am working on integrating Ionic Push into my Ionic application. After completing all the necessary setup and registration steps, everything seems to be functioning correctly. Testing with a curl request on both iOS and Androi ...

What is the best method for retrieving key-value pairs from an object based on a specific string filter?

const obj = { "pi_diagram": null, "painting": null, "heat_treatment": null, "welding_procedure": null, "inspection_test": null, "pipecl_hadoop": null, "pipecl": null, "ludo_min_hado ...

The appearance of Bootstrap-Navbar is altered when viewed on a mobile device

After creating a website that was compatible with both web and mobile devices, I encountered an issue where the navbar would not collapse on my smartphone. However, when I resized the browser window to match the size of the smartphone screen, it worked per ...

Unexpected behavior from JSON.stringify causing it to not return the desired objects

I have been experimenting with Node.js and Websockets lately. Making progress, but I encountered an unusual issue with JSON.stringify (client side). I use JSON.stringify to see which object properties the server is returning. For instance, this is the co ...

"Collaborative Drive" assistance within Google Apps Script

Currently, I am developing a JavaScript tool within Google Apps Script to analyze various document properties such as the validity of links and correct permissions settings. To achieve this, I have been utilizing the API outlined in https://developers.goog ...

How does the 'Route' parameter serve in the Restangular methods oneUrl() and allUrl()?

Check out the signature for the oneUrl function: oneUrl(route, url). Here's what the documentation says: oneUrl(route, url): Using this will generate a new Restangular object that points directly to a single element with the specified URL. I fin ...

I possess a list of unique identifiers and require the ability to either update an existing object within an array contained in a MongoDB document, if it exists,

I am facing a challenge in updating a specific element within an array in a MongoDB document. I have multiple IDs of that array and need to update the matching element using those IDs. data= [ { "planId" : "plan_FVNvrmjWT7fRDY", "startTime": ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

My issue lies in the execution flow with the child process in Node.js

I've been trying to create a function that takes an input string and returns an output string, but I'm facing challenges due to the delay in response. var result = "initial value"; function executeShell(command) { exec("uname&quo ...

Preventing Ng-repeat from refreshing after deleting using $http request

Once I remove an item from my list, the deleted object's data disappears, but the placeholder (empty row) lingers. (I tried using apply() with no luck) I have a standard CRUD interface displaying expenses. <table class="table table-striped"> ...

Sorting a list with Angular Sortable and Rails: Step-by-step guide

I'm facing a challenge with my project. I've developed an API using Rails and a client using Angular. Within my model called Todo, there is a property named order. When a new Todo is created, I automatically assign it an order value using the fol ...

Tips for efficiently executing npm run build without encountering any nuxt build errors

Recently, I encountered a frustrating issue with Nuxt build errors. When attempting to run the command npm run dev, my localhost server operates smoothly without any hiccups. However, upon executing npm run build, a series of errors like the one below surf ...