Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller.

Now that I have the response, I need to find a way to access it in the controller.

app.factory('logHomeService', function () {

        var getHomeService = function (LoginService, HomeService) {
            return
            {
                 LoginService.After("user", encodeURIComponent("pass"))
                  .then(function (response) {
                      debugger;
                      $stateParams.User = "admin";

                      var mydata = response.CT1SessionObj;


                      var DefaultModelObj = { cobj: mydata};

                      HomeService.pageLoad(DefaultModelObj)
                     .then(function (response) {
                         $rootScope.CT1SessionObj = response.mydata;



                     }, function (response) {
                         console.log("LoginService" + response.data);
                         alert(response.Message);
                     });

                  },

                      function (response) {
                          console.log("Home Service" + response.data);
                          return response.data;
                      });
                return response.data;
            };
        };
        return {
            getHomeService: getHomeService
        }

});

app.Controller('HomeController',function($scope,logHomeService)

{


this.logHomeService = logHomeService;
}

Now with this.logHomeService = logHomeService returning the method in the factory, I still need a way to extract the response result from the second service.

My goal is to return the home service response to the controller, with a console.log("Home Service" + response.data);

Answer №1

To effectively handle asynchronous operations in Angular, utilize promises and monitor the resolution within your controller.

app.factory('logHomeService', function($q) {
  var getHomeService = function(LoginService, HomeService) {
    // create a promise object
    var deferred = $q.defer();

    LoginService.After("user", encodeURIComponent("pass")).then(
      function(response) {
        $stateParams.User = "admin";
        var mydata = response.CT1SessionObj;

        var DefaultModelObj = {
          cobj: mydata
        };

        HomeService.pageLoad(DefaultModelObj).then(
          function(response) {
            $rootScope.CT1SessionObj = response.mydata;
            // resolve the promise
            deferred.resolve( response );
          }, 

          function(response) {
            console.log("LoginService" + response.data);
            // reject the promise if there is an error
            deferred.reject( response );
            alert(response.Message);
          });
      },

      function(response) {
        console.log("Home Service" + response.data);
        // reject the promise if there is an error
        deferred.reject( response )
      });

    // return the promise
    return deferred.promise
  };
  return {
    getHomeService: getHomeService
  }
});

Inject $q into the Factory and ensure to return the promise from the getHomeService() method.

The promise encounters 3 locations of resolution, with 2 rejections and 1 successful resolution. The rejections can be utilized in the controller to handle errors appropriately.

Now, update your controller to listen for the promise.

app.Controller('HomeController', function($scope, logHomeService){
  this.logHomeService = logHomeService;

  this.logHomeService.getHomeService().then(
    function(successResponse){
      // success
    },
    function(failureResponse){
      // failure
    }
  )
}

Answer №2

Thank you for your help, Grant. In the factory, I have been utilizing two services. One of the services involves promises, while the other one does not.

var service1 = function ($http, $q, configAPI) {  
    var crContractApi_Url = configAPI.crContractApi_Url;
    this.pageLoad = function (params) {
        var result = $q.defer();
        params.obj.data = null;
        $http({
            method: 'POST',
            url: baseurl + '/reatiler/retailer',
            headers: { 'Content-Type': 'application/json' },
            data: JSON.stringify(params)
        })
       .success(function (response) {

           result.resolve(response);
       })
       .error(function (response) {

           result.reject(response);
       });

        return result.promise;
    }

Service2 is implemented in a similar way. Are there any alternative methods?

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

Displaying a dropdown selection that showcases two object properties lined up side by side

I need the select option dropdown values to display employee names along with their titles in a lined up format. For instance, if my values are: Bob Smith Director Mike Kawazki HR Jane Doe Manager I want them to be shown as: Bob Smith Director Mi ...

Creating a session with AngularJS

One task I'm facing is transferring an object from one page to another. Specifically, when a user clicks on a search result on the results page, it should lead them to a page with relevant details. To achieve this, I attempted using services and facto ...

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

The deployed app on Heroku is showing a 304 status code with no JSON response

I've been working on a project using React, Express, and MongoDB. While everything works fine locally, I encountered an issue with GET requests after deploying the project on heroku.com. Instead of receiving the expected JSON response, I'm gett ...

Increase the border at the bottom while hovering with React.js and the Material UI library

Can someone help me achieve a hover effect similar to the one in this question on Stack Overflow: Hover effect : expand bottom border I am attempting to create the same effect in React using makeStyles of Material UI. Here is my current code: const useSty ...

jQuery toggle function not working properly on first click

Why does my first click not work, but the second one does? This is the code snippet: $(function () { $("#clickme").toggle(function () { $(this).parent().animate({left:'0px'}, {queue: false, duration: 500}); }, function () { ...

Handling AJAX requests in ASP.NET for efficient communication

I'm in the process of setting up ajax communication between a JavaScript frontend and an ASP.NET backend. While researching, I came across this sample code on w3schools: function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatecha ...

vue-router: error encountered while attempting to load asynchronous component for rendering

I'm new to vue-router and having trouble getting it to work. When I try to start my app, these errors pop up: [vue-router] Failed to resolve async component render: TypeError: _vm is undefined 49:16:39 [vue-router] uncaught error during route navigat ...

Issue with timebox filtering in customapp.js for Rally SDK 2

I am interested in creating a timebox filtered app and found an example at However, when attempting to run this on a custom HTML page, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) on th ...

The function array.push() is not achieving the intended outcome that I had in mind

Currently facing a rather frustrating issue. I'm attempting to utilize D3.js for dynamically plotting data (specifically, scores of individuals). Retrieving record data from a firebase database whenever changes occur - this is represented by an obje ...

Extract information from an external website using AJAX in Laravel

On my cart page, I utilize ajax to retrieve destination information from the user and provide them with shipping options to calculate their shipping cost. While everything is functioning properly, one issue remains: I am unsure of how to iterate through t ...

Display a message box in the external window just before the close event

I am trying to implement a message box that will appear when the user clicks the (X) button of an Ext window. However, I am facing an issue where the window closes before the message box is shown. Below is the code snippet I have written: var assignReport ...

Can you explain the meanings of <div class="masthead pdng-stn1"> and <div class="phone-box wrap push" id="home"> in more detail?

While working on styling my web pages with CSS and Bootstrap, I came across a few classes like "masthead pdng-stn1" and "phone-box" in the code. Despite searching through the bootstrap.css file and all other CSS files in my folders, I couldn't find a ...

Adding external stylesheets or libraries in Express is a simple process that can greatly

Currently, I am in the process of developing a todo application using the express framework on a node server. The starting point for my application is an index.ejs file located in the same folder as my jquery.min.js file. However, when I attempt to include ...

How can we incorporate a Material-UI skeleton to display API response data effectively?

I have incorporated the material-ui skeleton (Shimmer effect) to display data fetched from an API. { accountData.usersAccountData.map((userData, index) => ( // ...UI code ) ) } The output is shown below : https://i.sstatic.net/MEVhA.png It can be o ...

How to use mousedown event in Three.js to create line drawings

I've tried multiple approaches to achieve this effect. I'm looking to draw a line on mouse down event, and despite researching various resources, I haven't been able to come up with a solution. Currently, I'm utilizing the RayCaster met ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

"Contrasting the Execution of a JavaScript Function in a .js File Versus an HTML

I'm struggling with calling a JavaScript function inside an HTML page. Interestingly, when I move the function into an external file and link it, everything works perfectly. Can someone provide assistance in resolving this issue? Below is the content ...

Tips for receiving user input with custom values and assigning them to variables through multiple selection criteria using Jquery

I am encountering an issue with a form that contains multiple selection blocks. I am attempting to extract the values of each block criteria on click in order to send it to a database. However, every time I click on a block, my script retrieves all the val ...

What is the procedure for obtaining a Connect server's host name and port number?

Just like the example shown in this Express-related question, I'm wondering if there is a way to programmatically retrieve the host name and port number of a running Connect server? ...