Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have:

'use strict';
app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) {
    var out = [];

    if (authService.authentication.isAuth == false) {
        $location.path('/login');
        out = "effettuare login";
    }
    else {

        customerService.getCustomerAnagrafica().then(

            function (results) {

            out = results.data;

        }, function (error) {
            //alert(error.data.message);
        });
    }
    return { out: out };
}]);

I am trying to figure out how to properly return the value of results.data from this service.

I attempted using the _this = this; trick by placing it after .then(, but it did not work as expected.

My objective is to retrieve the results.data from this service.

This would allow me to easily call it in a controller like so:

$scope.myResults = loggedService.out;

Answer №1

Consider utilizing an Observer for this scenario; however, it may not be the optimal solution. It is recommended that your factory function returns a promise, which will then be used by your Controller to interact with $scope.

Whenever your service needs to communicate with the scope, ensure that promises are utilized accordingly for seamless integration.

Answer №2

By utilizing a closure instead of working with the promise, you are setting yourself up for a race condition. Essentially, if you try to access the closure before the asynchronous task has completed, you will not have the expected data.

Here is an example of what could happen in this scenario:

var closure = 'not yet';

var getReady = function(){
  var func = function(){
      closure = 'i am ready.';
    }
  setTimeout(func, 1000);
};

getReady();
alert(closure);
//The alert will show 'not ready yet' because it hasn't been updated yet (due to the 1000 ms timeout).

To avoid running into issues like this, it's important to continue working with the promise in a sequential manner.

function constructHouse() {
    var house = new Promise(buildHouse);
    var paintedHouse = house.then(paintHouse);
    var cleanHouse = paintedHouse.then(cleanHouse);
    return cleanHouse;
}
//You can then proceed to work with the returned promise in sequence:
constructHouse().then(sellHouse); 

Answer №3

Make sure to utilize a promise in your function. Here is an example code snippet, and please excuse any potential typos as I am currently working within a browser environment.

'use strict';
app.factory('loggedService', ['$q','$http', 'authService', 'customerService', function ($q,$http, authService, customerService) {

  var deferred = $q.defer();

  if (authService.authentication.isAuth == false) {
    $location.path('/login');
    deferred.resolve("Please log in");
  }
  else {
    customerService.getCustomerAnagrafica().then(
        function (results) {
        deferred.resolve(results.data)
    }, function (error) {
        //alert(error.data.message);
    });
  }
  return deferred;
}]);

You can then use loggedService.promise.then(function(data){ ....

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

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

Is there still a need to preload dynamic images in the background?

Imagine you have HTML code that includes an image with a placeholder: <img class="lazy-load" src="http://via.placeholder.com/150/?text=placeholder" data-src="http://via.placeholder.com/150/?text=real%20image"/> At some stage, you want to implem ...

How to retrieve and delete a row based on the search criteria in an HTML table using jQuery

Here is the HTML code snippet: <table class="table" id="myTable"> <tr> <th>Type</th> <th>Counter</th> <th>Remove</th> <th style="display:none;">TypeDistribution</t ...

The operation could not be completed with exit code 1: executing next build on Netlify platform

Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

Using ng-mouseover along with ng-if and an animated class causes issues

Whenever I hover over a link, it triggers a change in a variable value which then displays a <p> tag using ng-if. The code snippet looks like this: <div class="position text-center" ng-mouseover="social=1" ng-mouseleave="social=-1"> &l ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Use jQuery to set the onclick attribute for all elements rather than relying on inline JavaScript

I am currently facing a challenge with converting inline JS to jQuery. My goal is to eliminate all inline onclick events and instead target them by class. HTML - checkbox <td class="center"> <?php if ($product['selected']) { ?> ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...

Using AngularJS to Retrieve Data

Encountering an error in the console and unable to fetch data from MySQL. Looking for suggestions on resolving the following issue: Utilized AngularJS, PHP, MySQL, and MaterializeCSS Error: $http.get(...).success is not a function Below is the code sn ...

What is the process for rendering a page in node express from a route.post method?

My webpage fetches 100 memes from an API and displays them in a table. Each meme has a details button that should take the user to a specific page for that meme. However, even though my POST request to the meme route is successful, the meme details page is ...

"Jquery's .append function may sometimes display as undefined when

$("#clckjson").click(function() { $(document).ready(function() { $.getJSON("fuelj.json", function(data) { $(data).each(function(i, item) { console.log(item.stationID); var $table = $('<table>'); $table.a ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Creating AngularJS select boxes with varying sizes and values within an ng-repeat loop

I've identified the issue, but my attempts to resolve it have been unsuccessful so far. Any assistance would be greatly appreciated. Currently, I am working on generating a table from JSON data within an ng-repeat loop. One of the columns in the tabl ...

Utilize Javascript to load content dynamically while ensuring each page has a distinct link to individual content pages

As a newcomer to web development, I wanted to share my issue in hopes of finding a more efficient solution than what I've been attempting. Recently, I made changes to my website so that content is loaded dynamically using the jQuery load() function. T ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...