Tips for retrieving asynchronous AngularJS service data outside of the callback function

In my form submission process, I need to independently validate my email ID. Once the email ID is validated using the validationService, I will proceed with form submission and call formSubmissionService from my controller.

I aim to implement the logic in my formController as follows:

validationService.getEmailValidationResult.then(function(data){
    $scope.validEmailId = data.exists;
});

if($scope.validEmailId == true){
   formSubmissionService.submitForm().then(function(data){
      $scope.form.submitted = data;
   });
}

if($scope.form.submitted){
    $location.path('formSubmissionResponse');
}

After receiving feedback from previous posts, it was pointed out that the $scopevalidEmailId cannot be accessed outside of the callback function.

Therefore, the code should be adjusted as shown below:

validationService.getEmailValidationResult.then(function(data){
    $scope.validEmailId = data.exists;
    if($scope.validEmailId){
        formSubmissionService.submitForm.then(function(data){
            $scope.form.submitted = data;
            if($scope.form.submitted){
               $location.path('formSubmissionResponse');
            }
        )}; 
    }
});

Is there a better way to achieve this logic or can the rewritten code be further optimized?

Answer №1

When setting up a redirect, there is no need to assign to the $scope variable.

validationService.getEmailValidationResult().then(function(data){
    if (!data.exists) {
        return $q.reject(new Error('invalid email!'));
    }

    return formSubmissionService.submitForm();
})
.then(function(submit) {
    if (!submit) {
        return $q.reject(new Error('error during submission'));
    }

    $location.path('formSubmissionResponse');
})
.catch(function(e) {
    // handle error
});

Answer №2

If you want to simplify it further:

validationService.getEmailValidationResult.then(function(data){
    $scope.validEmailId = data.exists;
    if($scope.validEmailId){
       return formSubmissionService.submitForm();
    } else return $q.reject();
}).then(function(data){
     $scope.form.submitted = data;
     if($scope.form.submitted){
        $location.path('formSubmissionResponse');
     }
});

For additional details, check out:

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

Applying a value to all JSON objects within an array using AngularJS and JavaScript

Tale: I've developed an array ($scope.mainArray) that will be displayed in a <table> with <tr> elements using ng-repeat as shown below: +---+ | 1 | +---+ | 2 | +---+ | 3 | +---+ Each object contains an array which is presented within & ...

Navigating to the default landing page using basic authentication middleware in Express

I'm currently working on implementing basic authorization for an entire website using Express. The goal is to have users enter their credentials, and if correct, they will be directed to the standard landing page. If the credentials are incorrect, the ...

Issue with jQuery delegate and selector

I am attempting to assign a click event to all first anchor tags in all current and future divs with the "panels" class. My approach looks like this: $('#panel').delegate('.panels a:first', 'click', function(event) [...] How ...

Ramda Transitioning to a Liberated Style of Programming

Unable to find a suitable resource for this particular issue. I apologize if this question has already been asked, but my attempts to locate the answer have proven fruitless (perhaps due to a lack of effective search methods). I've developed a functi ...

Issue with Ajax call not triggering the Controller Action in MVC

I am encountering an issue with making an ajax call to the controller action method that returns a json object. In addition, I need to pass the integer CheckID to the method. Any assistance would be greatly appreciated. Thank you in advance! ***View*** ...

How to use JavaScript to identify the CSS property value of an HTML element

Everything seems fine until the alert pops up, but the 'if' statement is not executing properly. Here is the program stack. Is there a way to check the display property of a div to see if it's set to "block" or "none"? for(i=1;i<=10;i++ ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

Issue with JQUERY where HTML select element is not visible

$(document).ready(function(){ var selArr = [ {val: 'corsair', text: 'Corsair'}, {val: 'evga', text: 'EVGA'}, {val: 'antec', text: 'Antec'} ]; $('#pSupply& ...

Getting the name and value from an object

Just starting out with Javascript and Nodejs, using express and making a call to the following link: localhost:7080/v1/movies/order/notify/insert?breed=Whippet&age=10 After that, I am attempting to extract the property name along with its correspon ...

How can I use JavaScript to optimize and cache an HTML video element when the streaming size exceeds the file size?

Currently, I have successfully set up a video streaming feature using a NodeJS server. The issue I am facing is related to the video size, which is 61MB. Whenever I adjust the range in the HTML video element, it triggers another fetch request, leading to a ...

The Node program does not pause for the loop to finish executing

I've attempted to utilize async/await and promises, but I'm having trouble getting this code to execute sequentially. The script loops through a document, parses it, saves the data to an array, and then writes the array to a .json file. However ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...

Issue with Retrieving the Correct Element ID in a Loop with JavaScript Function

I'm in the process of developing a dynamic wages table with HTML and JavaScript to compute each employee's wage based on input from each row. In order to achieve this, I've utilized a loop to assign a unique ID to the total cell in every ro ...

Creating custom directives that utilize recursive behavior within an ngRepeat loop

I am in the process of building a treeview using AngularJS. Below is the code I have so far: module.directive('treeview', function () { return { restrict: 'E', templateUrl: "/templates/ui/controls/treeview.htm", ...

Is it possible to obtain a user's public URL using the Facebook API in version 2?

In version 1, it is possible to obtain the user's public link by using the following endpoint: /v1.0/me function testAPI() { console.log('Welcome! Fetching your information....'); FB.api('/me', function(response) { ...

Struggling to make a click event work in aframe

Attempting to develop an inventory system for a game using the AFrame library has been quite challenging. I have a specific custom component in place that should make the item I am picking up invisible while making the in-hand item visible. However, for so ...

Can the CSS property of a class be altered in real-time with jQuery?

I am working on a project where I have a predefined CSS style in one class. I am currently attempting to load that page as an IFRAME on another website. My goal is to modify the CSS property of that specific class from the loaded site using jQuery. Unfor ...

The onChange function in Material UI Text Field is preventing users from inputting additional values

My application contains a custom TextField component. I am facing an issue where I cannot increase the value of the first TextField due to the presence of the onChange method. However, the second TextField does not have the onChange method, and I can succe ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...