Problem with AngularJS factory causing issues with promises

I have a factory in AngularJS set up like this:

'use strict';

angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {

                var args = {};

                return $http.post(urlBase + 'api/investor/payment/create', args);
            }
    });

I want to utilize this factory inside a controller as shown below. The key point here is handling different scenarios based on whether the request was successful or encountered an error.

$scope.order = function () {
            console.log('PaymentCashCtrl.order');
            $scope.disabledButtons.submitCashOrder = true;

            paymentService.create()
                    .then(
                            function (response) {
                                // do something with response


                            }, function (error) {
                                // do something with an error
                        }));
        };

My challenge is that I wish to update some fields within the paymentService once the $http.post response is resolved and then return the promise so that the callbacks in the controller, namely function(response) and function(error), continue to work.

I attempted the following approach:

return $http.post(urlBase + 'api/investor/payment/create', args)
                        .then(function(response){
                            console.log(response);
                            this.response = response;
                            return response;
                        });

However, this method does not work as the function(error) handler in the controller is never triggered.

I aim to keep using my controller handlers while also updating certain aspects when the $http.post response is resolved.

Thank you.

Answer №1

When working in the factory setting, it is important to ensure that the paymentService object is returned. It is also crucial not to resolve the promise within the factory itself, but instead handle the resolution in the controller.

.factory('paymentService', function($rootScope, $http, config, tools) {
    var urlBase = config.baseUrl;
    var paymentService = {

        response: {},

        create: function() {

            var args = {};

            return $http.post(urlBase + 'api/investor/payment/create', args);
        }
    }

    return paymentService;
});

$scope.order = function() {
    console.log('PaymentCashCtrl.order');
    $scope.disabledButtons.submitCashOrder = true;

    paymentService.create()
        .then(
            function(response) {
                // perform actions with response

            },
            function(error) {
                // handle the error appropriately
            }));
};

Answer №2

Utilize the variable $q

Modify your factory script as follows:

angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools, $q) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {
                var deferred = $q.defer();
                var args = {};

                $http.post(urlBase + 'api/investor/payment/create', args)               
                .then(function(response){
                        console.log(response);
                        paymentService.response = response;
                        deferred.resolve(response);
                    }, function (error) {
                         deferred.reject(error);
                    });
                return deferred.promise;
            }
         };

      return paymentService;
    });

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

Determining the scrollWidth of a div with an absolutely positioned child div

Having some trouble determining the width of a div's content instead of the div itself. The typical solution would involve using Javascript's scrollWidth property. However, there is a complication in this case. Inside the div, another div is ab ...

Encountering issues when attempting to incorporate ng-bootstrap into an AngularJS project

Having trouble injecting ng-bootstrap into my Angular module. I keep getting an error. <script type="text/javascript" src="js/lib/jsapi.js"></script> <script type="text/javascript" src="js/lib/jquery.min.js"></script> <scr ...

Implementing dynamic data binding in JavaScript templates

I've been experimenting with jQuery and templates, and I managed to create a basic template binding system: <script type="text/template" id="Template"> <div>{0}</div> </script> Furthermore... var buffer = ''; v ...

At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening. Click Here to See the Unwante ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Can you explain the distinction between "javascript:;" and "javascript:" when used in the href attribute?

Can you explain the distinction between using "javascript:;" and just "javascript:" within an anchor tag's href attribute? ...

JavaScript timekeepers and Ajax polling/scheduling

After looking into various methods like Comet and Long-Polling, I'm searching for a simpler way to push basic ajax updates to the browser. I've come across the idea of using Javascript timers to make Ajax calls at specific intervals. Is this app ...

Tips for refreshing a live ajax call to animate a circle

Currently, I am utilizing the gaugeMeter plugin to dynamically display the CPU usage of my elasticSearch Host. While the values are being displayed correctly, there seems to be an issue with the animation of the gauge/circle itself. Instead of the indicato ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

How can Vue.js transfer form data values (using v-model) from a Parent component to a Child component?

I am working on a multistep form using vue.js. The parent form collects two inputs and once these are validated, it moves to the next step which involves a child component. I want to pass the values from the parent component to the child component's f ...

Utilizing Angular.js to extract data from a deeply nested array of objects in JSON

Hello, I am currently learning about Angular.js and working on developing a shopping cart. In this project, I need to display an image, name, and cost of each product for multiple tenants. Each tenant has an array called listOfBinaries which contains listO ...

Attempting to call a Struts 2 action class from AngularJS using an HTTP GET request, however, no response is being received

I have been working on a simple application that involves making a call to Struts 2 through AngularJS. The process includes sending an HTTP GET request from AngularJS to fetch JSON data from the server. On the server side, I have created an action class na ...

How can AngularJS effectively parse JSON data containing HTML elements?

We are experiencing difficulties in reading a json file containing html content. Here is the code snippet with the json data we are working with: Json data: { "aboutContent": { "listItems": [{ "title": "Investors", "de ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

In both Chrome and Edge, the default value for the <select> tag is successfully set, however, this functionality is not working in

I have defined two values in the created method, 2018 and My Name, and assigned them to separate data properties. These data properties are then passed as v-bind to a component. The issue I am facing is that in Chrome and Edge, both values are set as defa ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...

What's the issue with the submit button not functioning on the form?

After downloading a sample form, I encountered the following code: <form id="login-user" method="post" accept-charset="utf-8" action="/home.html" class="simform"> <div class="sminputs"> <div class="input full"> <l ...

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

Customizing an image with personalized text and then sending it to a server using a combination of javascript and

Looking for a way to add text to an image saved on the server, then save the edited image back to the server. I've heard using canvas is the best approach, but struggling to find the specific solution I need. ...