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

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

Detecting changes in arrays in Vue.js 2

Below is a simplified version of the code : <template> /* ---------------------------------------------- * Displaying a list of templates, @click to select the template /* ---------------------------------------------- <ul> ...

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

Crafting personalized objects from an array

In the process of creating an object from an array, I am faced with a dilemma. The elements in the array are as follows: var arr = [ 'find({ qty: { $lt: 20 } } )', 'limit(5)', 'skip(0)' ] Despite my efforts, my code is ...

Utilize a single array to point to multiple elements

I am curious about the potential to create a unique scenario using JavaScript. Imagine having two arrays: a = [1, 2, 3] b = [4, 5, 6] What if we could combine these arrays into a new array, c, that encapsulates both: c = [1, 2, 3, 4, 5, 6] The intrigui ...

JavaScript function overriding allows a subclass to provide a specific implementation of

I have a JavaScript file with two methods: var DBProcessing = function() { console.log("ok") ... } var DBProcessing = function(str) { console.log(str); ... } When calling DBProcessing(), I am only getting an output of undefined. Is there a way to expli ...

What is the best way to set up a simple example using a Node Stream.Readable?

I am currently exploring the concept of streams and encountering some difficulties in making it work properly. For this scenario, my goal is to send a static object to the stream and then pipe it to the server's response. This code snippet shows my ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

The Gateway to Github: Unveiling the Mysteries through a

I need assistance in creating a static web page that can extract and showcase all the latest pull requests from a specified GitHub repository. My intention is to utilize octokit.js, but it seems to be designed for node.js. Is there any simple approach to ...

Sending information to an Ionic popover within an ng-repeat loop

Struggling to integrate Ionic Popover into my application under ng-repeat. How can I pass a parameter to it? <p ng-repeat="query in ctrl.timesheet">query.Name<button ng-click="openPopover($event)">Open Popover</button></p> <scr ...

Dropzone JavaScript returns an 'undefined' error when attempting to add an 'error event'

When using Dropzone, there is a limit of 2 files that can be uploaded at once (maxFiles: 2). If the user attempts to drag and drop a third file into the Dropzone area, an error will be triggered. myDropzone.on("maxfilesexceeded", function(file){ a ...

Exploring a Discord.js collection: tips for accessing and manipulating objects within an array in the collection

I have a discord.js Collection that contains information about dispatcher and queue objects. Here is the structure: Collection(1) [Map] { '403547647215927306' => { dispatcher: StreamDispatcher { _writableState: [WritableState], ...

Modify background image upon hovering using AngularJS

I cannot seem to make the background images of my divs change. Despite trying various options, none of them have been successful. Here's an example of my code: <div ng-controller="mainController" class="main"> <div ng-repeat="land in lan ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...