combining multiple API requests and processing before returning promise from factory method

For quite some time, I've been relying on the promise generated by a simple http method. However, my current need involves chaining multiple API calls, processing the data, and then returning that processed data. The issue I'm encountering with my existing setup is that the factory isn't returning the promise, causing it to not wait for the data before moving on to the next line in the controller.

app.factory('mytestService', ['$http', function($http){
    getSomeDataById: function(id){
    var userAllProjects = [];
     var myHelperService = this.getSecondData;
     this.getFirstData(id).then(function(response){ // first api call
         var idObjectValue = response['result'][0]['id'];
         myHelperService(idObjectValue).then(function(response){ //second api call
           userAllProjects= response['projectList']
        });
   });
    return userAllProjects
   }
]);

Now, when attempting to access in the controller:

$scope.allProjects = mytestService.getSomeDataById(1234);
console.log($scope.allProjects);

the console displays undefined. It's clear that this happens because it doesn't wait for the service to complete before moving on to the next line.

I am new to Angular promises and would appreciate any guidance on how to address this issue. Feel free to ask if you require more details.

Answer №1

Presenting a new concept called Promise Chaining, which is generally favored over the creation of new deferred

fetchDataById: function(id){
    var userProjects = [];
	var helperService = this.retrieveAdditionalData;

    // Instead of creating a new promise, 
    // return the existing one to avoid unresolved promises if any call in the chain fails
    return this.fetchFirstData(id).then(function(response){ // initial API request
        var idValue = response['result'][0]['id'];
        return helperService(idValue);  // secondary API request
        // Avoid chaining .then here for better readability, 
        // it can be moved to the outer layer

    }).then(function(response){
        userProjects = response['projectList'];
        // Return necessary data for use in .then of fetchDataById() here
    });
});

Answer №2

Instead of using then in your controller, you can integrate it within the controller itself.

Factory

app.factory('mytestService', ['$http', function($http) {
    getSomeDataById: function(id) {
        var myHelperService = this.getSecondData;
        return this.getFirstData(id);
    },
    secondApiCall : function(idObjectValue){
      return myHelperService(idObjectValue);
    }
}]);

Controller

mytestService.getSomeDataById(1234).then(function(response){
  mytestService.secondApiCall(response['result'][0]['id']).then(function(response2){
    $scope.allProjects = response.data;
  })
});

Answer №3

Check out the following code snippet.

fetchDataById: function(id){
  var userDataPromise = $q.defer();
  var myService = this.getSecondData;
  
  this.getFirstData(id).then(function(response){ // first API call
     var idValue = response['result'][0]['id'];
     
     myService(idValue).then(function(response){ //second API call
       userDataPromise.resolve(response['projectList']);
    });
  });
  
  return userDataPromise.promise;
}

The concept here is to create a deferred object initially and then return the promise. Once the data is retrieved, resolve the deferred object which will make the data available in your controller.

Please note that you must include $q as a dependency for this to work correctly.

Reference: https://docs.angularjs.org/api/ng/service/$q

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

After some time, socket io begins duplicating its posts in my basic chatroom

I am currently in the process of developing a chatroom using node.js and socket.io. It is still in the early stages as I am learning these languages. The issue I am facing is that when appending text from a text box to a div, it occasionally duplicates for ...

Angular version 1.63 with UI-Router version 1.0 brings a new feature: local transition hooks that

I am in search of a transition hook event specific to my application's local environment. For instance, Whenever controller A is instantiated, I aim to have all transitions from state foo to state foo.bar be recorded. While going through the Transiti ...

What are some effective methods for optimizing GLSL/C code in Three.JS when using PerObject-Blur?

UPDATE 2 I have successfully integrated custom attributes using THREE.js. Each pass in the vertex shader is now aligned with the position attribute, resulting in an efficient solution with minimal code. An example will be added later UPDATE 1 This me ...

Post-render for HTML linkage

Is there a method to execute customized code after Knockout has inserted the html into the DOM and completed rendering? This is required in order to bind a nested view model to dynamically generated html code. Perhaps like this: <div data-bind="html: ...

Error message: The variable datepicker_instActive is not defined within Jquery-ui Datepicker

Having trouble with a Rails + Angular app where I've implemented the jquery-ui datepicker. The console is showing an error that says: TypeError: datepicker_instActive is undefined if(!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? ...

Using Node.JS and MySQL to optimize data retrieval by combining queries to define variables and select data efficiently

My SQL query that functions perfectly in PHPMyAdmin seems to be causing issues in Node.JS: SET @row_number=0; SELECT * FROM blah blah @row_number blah blah; When attempting to execute both queries in Node.JS using con.query("SET @row_number=0; SELECT * ...

Unable to send a request to ASP.NET MVC action while utilizing AngularJS Routeprovider

I'm encountering a problem with the angular route provider. Here is the route configuration in app.js: fmApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ $locationProvider.html5Mode( ...

Having trouble reloading an iframe src/location with a new URL in Safari?

Initially, my page loads with just a form inside an iframe. Here's an example: <iframe id="oIframe" ...src='somePage>' <form ... /> </iframe> Upon clicking a button in the form, certain javascript code is executed to cr ...

When working with TextareaAutosize component in MUI, an issue surfaces where you need to click on the textarea again after entering each character

One issue that arises when using TextareaAutosize from MUI is the need to click on the textarea again after entering each character. This problem specifically occurs when utilizing StyledTextarea = styled(TextareaAutosize) The initial code snippet accompl ...

Is there a way to automatically redirect to a 404 page when a promise is rejected in the route configuration of Angular?

How should a client be directed to an error route in Angular when the API returns a 404 error while attempting to load a resource based on the parameters in the URL? In scenarios where a user accesses a page like orders/1, they should see the order detail ...

One-page website utilizing JSP MVC framework

I'm in the process of familiarizing myself with Angular and JSP, and I have a query pertaining to the overall architecture of a single-page system. I grasp that JSP MVC comes equipped with security functionalities that are vital for conditionally serv ...

The Signature Pad loses its focus

My HTML code is using JavaScript with Bootstrap and the Signature Pad. The issue I am facing is related to the Bootstrap Collapse feature. When I set the first panel as default, the Signature Pad does not allow me to sign. However, if I set the third panel ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Is there a way to hold off passing props until after setState() has completed?

I wrote a function named renderLayers that iterates through each object in the filterState array and copies those with the checked property set to true. const [layers, setLayers] = useState([]); (...) const renderLayers = () => { const ne ...

Ensuring the continuous transmission of data frames is essential for WebSocket communication

Our system utilizes websocket technology to transmit user activity events such as clicks, mouse movement, scroll, input, and more. In addition to these events, we also send a snapshot of the HTML DOM. On average, the size of the HTML snapshot is approximat ...

"Implementing a jQuery script in PHP to provide real-time feedback on an upload form within an

Here is the HTML code I am using for my file upload: <div id="status"></div> <iframe name="upifrm" src="" style="display:none;"></iframe> <form name="myForm" id="myForm" action="upload.php" method="post" enctype="multipart/for ...

Unable to view the HTML division

I am struggling with my website creation as I encounter issues with the .Main div. Despite setting background-color: orange; in the CSS, the color is not visible on the page. The inspector shows that it is positioned at 1440 x 0. Any assistance would be gr ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Utilizing React Native to dynamically generate buttons through a loop

I am currently working on retrieving data from the Eventbrite API. The information I am hoping to extract is the event names, which will then be added to a list. Within the render function, I aim to dynamically create buttons based on the number of event ...