Leveraging a factory value within another factory in AngularJS

Greetings! I am currently working on a web application using AngularJS. Within my project, I have a JavaScript file containing two factories that make HTTP calls to a web API. My goal is to utilize the output of one factory within another factory. Below is the code for my initial factory:

myapp.factory('sadadpaymentapi', ['$http', '$cookieStore', 'cfg', 'ScrollFunction', 'leaselisting','$q', function ($http, $cookieStore, cfg, ScrollFunction, leaselisting,$q) {
    var sadadpaymentapiobject = {};
    var baseurl = cfg.Baseurl;
    var LoginID = $cookieStore.get("LoginID");
    var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
    var urlapi = baseurl + "api/ServiceRequest/CreateRSSedad/";
    sadadpaymentapiobject.callsadad = function (PaymentType) {
        var request = {
            url: urlapi,
            method: 'POST',
            data: {
                SRActivityID: LoginID,
                PaymentType: PaymentType,
                PaymentAmount: "100" //Need to get value from another factory
            },
            headers: ScrollFunction.getheaders()
        };
        return $http(request);
    }
    return sadadpaymentapiobject;
}]); 

Next, we have another factory that provides the required value for the PaymentAmount parameter in our previous factory.

myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction','$q', function ($http, $cookieStore, cfg, ScrollFunction,$q) {
    var leaselistingobject = {};
    var baseurl = cfg.Baseurl;
    var LoginID = $cookieStore.get("LoginID");
    var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
    leaselistingobject.getValue = function () {
        var requestObj = {
                                url: baseurl + "api/ServiceRequest/GetROLSPSRLeaseList/",
                                method:'POST',
                                data: {
                                    LoginID: LoginID,
                                    AccountNumber: $cookieStore.get("AccountNumber")
                                },
                                headers: ScrollFunction.getheaders()
                    };
        return $http(requestObj).then(function (response) {
            return response.data;
        });
    }
    return leaselistingobject;
}]);

When attempting to inject

PaymentAmount: leaselisting.getValue()
and checking the console log with
console.log(leaselisting.getValue());
, a Promise {$$state etc. is returned. Referencing the provided screenshot, what I require from this setup is the variable AccountNumber.

In my first API call, rather than hardcoding PaymentAmount: "100", I aim to retrieve it from the other factory. Any guidance on achieving this would be greatly appreciated. Thank you.

Answer №1

Embed the factory into another factory and follow the same steps as you would in a controller,

myapp.factory('rentallist', ['$http', '$cookieStore', 'config', 'ScrollBehaviour','$q','paymentapi', function ($http, $cookieStore, config, ScrollBehaviour,$q,paymentapi) {

Answer №2

leaselisting factory includes a method called getValue that makes an asynchronous call and resolves it.

Here is an example of how you can use it:

// ...
var request = {
        url: urlapi,
        method: 'POST',
        data: {
            SRActivityID: LoginID,
            PaymentType: PaymentType,
            PaymentAmount: leaselisting.getValue();
        },
 // ...

You can see a demonstration in Fiddle that illustrates your situation. Since the second async call depends on the first one, I recommend using a Promise chain. In this case, I have simulated the async call with $timeout to return part of the address (in your case, it is PaymentAmount), resolved it with a promise, and then made another Promise call using $http.

app.controller('fessCntrl', function ($scope, sadadpaymentapi) {

    $scope.alertSwap = function () {           
        $scope.data = sadadpaymentapi.getData();    
    }; 
});

app.$inject = ['$scope', 'leaselisting'];

app.factory('leaselisting', ['$timeout','$q',  function($timeout, $q) {    

       var leaselistingobject = {
            getValue: function () {              
               var deferred = $q.defer();               
               $timeout(function(){                  
                return {address: 'Singapore, SG, Singapore, 153 Bukit Batok Street 1'};
               }, 3000).then(function(val){
               deferred.resolve(val); 
               });              
                return deferred.promise;
            }

       };       
        return leaselistingobject;
}]);


app.factory('sadadpaymentapi', ['$http','$q','leaselisting', function($http, $q,leaselisting) {  

       var leaselistingobject = {
            getData: function () {    

               var URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=';  

               return leaselisting.getValue().then(function(result){

                URL = URL + result.address + '&sensor=true';

                 return $http({method: 'GET', url: URL})
                }).then(function (response) {
                   return response.data;
                 });
            }

       };       
        return leaselistingobject;
}]);

Answer №3

If you want to retrieve the account number in your controller, you can follow this example:

 leaselisting.getValue().then(function(response){
         // Obtain the account number here and pass it to another factory
           var accountNumber = response.data.AccountNumber;
          sadadpaymentapi.callsadad (accountNumber ).then(function(response){
                 // Deal with the final response here
          });
    });

Here is the code for the Factory:

myapp.factory('leaselisting', ['$http', '$cookieStore', 'cfg', 'ScrollFunction','$q', function ($http, $cookieStore, cfg, ScrollFunction,$q) {
        var leaselistingobject = {};
        var baseurl = cfg.Baseurl;
        var LoginID = $cookieStore.get("LoginID");
        var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
        leaselistingobject.getValue = function () {
            var requestObj = {
                                    url: baseurl + "api/ServiceRequest/GetROLSPSRLeaseList/",
                                    method:'POST',
                                    data: {
                                        LoginID: LoginID,
                                        AccountNumber: accountNumber
                                    },
                                    headers: ScrollFunction.getheaders()
                        };
            return $http(requestObj)
        }
        return leaselistingobject;
    }]);

Remember to inject both factories into your controller.

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

Tips for concealing a tab within Angular Bootstrap UI using ng-show/ng-hide

Angular Bootstrap UI is being utilized to display a tabset. The necessary script, ui-bootstrap-tpls-0.6.0.min.js, and some HTML template files are included in the setup. Check out the following markup: <tabset> <tab ng-hide="!hideme"> ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

Android textView is populated with randomly generated alphanumeric text after parsing file

I have a parse file coming from parse.com as a string message, and I need to display it in a textView. ParseFile file = message.getParseFile(ParseConstants.KEY_FILE); String filePath = file.getDataInBackground().toString(); if (messageTy ...

What is the procedure for iterating through the square brackets of a JSON array?

Here's the data I have: $json_data_array = '[ { "id": 1, "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd7cdffcbdacccb91dcd0d2">[email protected]</a>", ...

AngularJS synchronous function call

METHOD 1 { let myform = retrieveForm(); let myData = $sce.trustAsHtml(myForm); } METHOD 2 let retrieveForm = function () { let form = ""; //Custom service for API call .then( function (response) { form = //processing lo ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

Closing a Javascript-created popup using server-side code

I'm encountering an issue with closing a modal that I've created in JavaScript. The goal is to display a loading spinner while data is being fetched, and then hide it once the background process is complete. Everything functions correctly until t ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Why is my Laravel function retrieving outdated session data?

Currently, I am in the process of developing a shopping cart feature using session. My goal is to create a function that can update the quantity of an item in the shopping cart and refresh both the subtotal and the list of items in the cart displayed on th ...

Troubleshooting the malfunctioning of the Bootstrap slide animation

I've been attempting to implement scroll animation on a div, but for some reason, it's not working as intended. I must have made a mistake somewhere, but I can't figure out where. Any help in resolving this issue would be greatly appreciated ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

Guide on creating an AJAX request for a POST method

I am new to working with AJAX, and I have been trying to use it for a POST function similar to the curl command below: curl -X POST -H 'Content-type:application/json' --data-binary '{ "replace-field":{ "name":"sell-by", "type":"date", " ...

Trouble with the display none function

I am trying to achieve the following: If my shopping cart is empty, I want another div to display over the top of it. Instead of seeing the cart, users should see a message saying 'your cart is empty'. Currently, I have set the other div to dis ...

Firestore version 9 - Retrieve nested collection depending on a string being present in an array

Working on a new chat application here. It has been a while since I last used Firestore. I am currently using v9 and facing an issue with retrieving the nested "messages" collection when the "users" array in the document contains a specific ID. I have man ...

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

What is the best approach for finding the xPath of this specific element?

Take a look at this website Link I'm trying to capture the popup message on this site, but I can't seem to find the element for it in the code. Any ideas? ...

Angular Controller setup

One common question that often arises is whether placing 'ng-controller' under 'ng-app' in the HTML file negates the need to register the controller in JavaScript. Does it create any issues if the controller is scoped under 'ng-app ...

Accessing attribute value of selected option in AngularJS select element

I have a select tag that displays options, and I want it so that when an option is selected, the value of the data-something attribute is copied into the input element. This is just for demonstration purposes; the actual value should be sent in the form. ...

Issues with integrating VUE frontend with PHP backend and API

Apologies for any language mistakes as English is not my native tongue. I hope my message is clear enough. We are in the process of developing a user system where users, upon logging in, can perform various actions such as joining events, updating their p ...