What is the process for sending a response back to a function from .then() in Angular?

When the html calls check(), it should return either true or false.

ng-class="{'timeline-inverted: check(id)'}"

The server script's $scope.server.get() retrieves a result(r) from the server, which needs to be returned to the check() function as $scope.result.

Below is my Angular code:

$scope.check = _.memoize(function(userId) {
    $scope.server.get({
        action: 'checkif',
        userID: userId
    }).then(function successHandler(r) {
        $scope.result = r.data.result;
    });
    return $scope.result;   // $scope.result is currently undefined
});

Answer №1

Generate a fresh Promise that is only resolved once the HTTP request is completed successfully.

$scope.verify = _.memoize(function(userId) {
  return new Promise((resolve, reject) => {
    $scope.server.get({
      action: 'verifyUser',
      userID: userId
    }).then(function successfulResponseHandler(r) {
      resolve(r.data.result);
    });
  });
});

Answer №2

It may not be advisable to use memoize in this scenario, as it works well with primitive types but the API call might return different data sets for the same userId and action parameters!

Consider moving your $http call from being bound to an $scope to a service for better organization. Your application structure could be enhanced like this:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, user) {

   $scope.userData = null;

   user.get('checkif', 2).then(function (result) {
      $scope.userData = result.data.result;
   });
});


myApp.service('user', function () {
  this.get = function (action, userId) {
    return $http({
      url: 'http://your-api-endpoint/',
      method: 'GET',
      params: {
        action: action,
        userID: userId
      }
    });
  }
});

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

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

`I'm experiencing issues with my AJAX call when using Django`

As part of my blog practice, I'm trying to ensure that all notifications are marked as seen when a user views them. This functionality works fine when I manually go to the URL, but it's not working when using Ajax. Here is the JavaScript code: ...

Unable to retrieve data from MySQL Database using Express Route

Struggling to understand how to execute a MySQL database query within the promise in my route file. Currently, I am developing a RESTful API for interacting with a MySQL database using GET methods. The technologies being utilized are Express for the backen ...

Create a Sleek Dropdown Navigation Menu with MaterializeCSS in WordPress

I am having trouble displaying the dropdown menu on my WordPress website. How can I make sure the dropdown menu appears properly? functions.php register_nav_menus( array( 'primary' => __( 'Primary Menu', 'TNCTR-OnePage' ) ...

Can you please explain the concept of a state provider and root provider in a library file where it is

Hello there, I am new to angularjs and I have a question about the state provider and root provider. Why do we inject ['ngRoute'] in rooteProvider and ['ui.router'] in stateprovider? I am really confused about this, so please explain br ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

The Stylish Choice: Materialize CSS Dropdown Selector

I am currently integrating Materialize CSS into my application and have used media queries to ensure that the layout is responsive. However, I am facing an issue with a select dropdown element. It works fine on laptops but does not allow for selecting any ...

Manipulate private variables in Java

Greetings, As a beginner in the world of JAVA, I find this programming language absolutely fascinating. My query pertains to the scenario below: Imagine having a class structured like so: public class Person{ private String firstName; private Stri ...

The backtick is not functioning correctly when trying to append the result in the Internet Explorer browser

I am using the .html method to append HTML content to a specific div ID within my file. <html> <head> Title <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> ...

Incorporating Restangular data into the $scope object for a collection

After working tirelessly on API integration all day, I finally turned to Restanglar for help. However, I am encountering difficulties extracting the data and injecting it into $scope. I am aware that the data returned from the API is not just plain JSON, ...

Guide on creating a dynamic line segment in real-time with three.js

Just delving into the world of Three.js and aiming to replicate the drawing technique seen in Microsoft Paint for creating line segments. My goal is to capture the coordinates of a point onMouseDown and continue extending a line with onMouseMove until re ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Mapping Dropdown values into another dropdown within AngularJS

I'm facing an issue with my dropdown menu. It has two options: Randomslab and standard style. When I select Randomslab, I want only one value to appear in the next dropdown (300*300). On the other hand, if I choose standard style, then all values sh ...

Observable - transforming two promises into an observable stream

I am facing a common scenario where I am looking to chain two promises together in such a way that if the first promise fails, the second promise needs to be canceled. In the world of 'Promises', the code would look something like this: Fn1.doPr ...

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

Steps for displaying a customized view within an NPM module:

Given that pushAsset prohibits loading external resources, I am interested in displaying this template/script from my NPM module: views/tag.html <script async src="https://www.googletagmanager.com/gtag/js?id={{ data.gid }}"></script> NPM mod ...

Attempting to implement a unique filter on an ng-repeat that was crafted with creativity

In my current project on Ionic, I have been working on creating a screen that resembles a gallery. It consists of rows with three items in each row. The content is retrieved from a backend, so the code needs to dynamically scale as more items are fetched. ...

React Select value remains unchanged after state modification

I'm facing an issue with a select component that should reset to the "Neutral" state after the user clicks the next button. However, it keeps displaying whatever option the user previously selected. The components are structured as shown below. When t ...