AngularJS does not run the code inside the ref once directive

Code within the block of this.verifyUserToken does not execute. It appears that the issue may stem from asynchronous calls, as the data returned is not yet available. I am unsure of how to proceed in handling this.

this.verifyUserToken = function(){
            //Check if token matches existing token and if verified is true
            ref.orderByChild('token').equalTo(this.token).once('value').
            then(function(dataSnapshot){
                //If token matches
                    if(dataSnapshot.val()){
                        alert("Token Exists",dataSnapshot.val().token);
                        $scope.isVerified = "YES";
                    }else{
                        alert("Token does not exist",dataSnapshot.val());
                        $scope.isVerified = "NO";
                    }
            });
        }

this.registerUser = function(){
            console.log("Entered registerUser()");

            this.verifyUserToken();
            alert("The Value of isVerified:"+ $scope.isVerified);
            if($scope.isVerified == "YES"){
                    alert("Verifying User Token...",this.verifyUserToken());
                    $scope.auth.$createUser({
                    "email": this.email,
                    "password" : this.password
                }).then(function(userData){
                    alert("Successfully created user account with uid:", userData.uid);
                    //redirect to /userlogin if registration is successful
                    //this.changeVerifiedStatus();
                    alert("User verifed and changed");
                    $location.path('/userlogin');
                }).catch(function(error){
                    alert("Error Creating User:",error);
                });
            }else{
                alert("Token failed verification");
            }   
            };

Answer №1

When dealing with the asynchronous call to firebase in the function verifyUserToken, it is important to handle it by returning a Promise from this function. This way, you can ensure that the registerUser function is only executed after the verification call has been completed.

A demonstration of this functionality can be seen in this jsFiddle.

this.verifyUserToken = function(){
  //Check if token matches existing token and if verified is true
  var verifyUserTokenPromise = new Promise(function(resolve, reject){                                               
    ref.orderByChild('token').equalTo(this.token).once('value').then(function(dataSnapshot){
      //If token matches
          if(dataSnapshot.val()){
              alert("Token Exists",dataSnapshot.val().token);
              $scope.isVerified = "YES";
          }else{
              alert("Token does not exist",dataSnapshot.val());
              $scope.isVerified = "NO";
          }
          //resolve the promise. you can pass any data here
          resolve($scope.isVerified);
    });
  });
  return verifyUserTokenPromise;
};

this.registerUser = function(){
  console.log("Entered registerUser()");

  this.verifyUserToken().then(function(result){
    alert("The Value of isVerified:"+ $scope.isVerified);
    if($scope.isVerified == "YES"){
            alert("Verifying User Token...",this.verifyUserToken());
            $scope.auth.$createUser({
            "email": this.email,
            "password" : this.password
        }).then(function(userData){
            alert("Successfully created user account with uid:", userData.uid);
            //redirect to /userlogin if registration is successful
            //this.changeVerifiedStatus();
            alert("User verifed and changed");
            $location.path('/userlogin');
        }).catch(function(error){
            alert("Error Creating User:",error);
        });
    }else{
        alert("Token failed verification");
    }   
  })
};

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

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...

When I try to run "npm start" with node-webkit, it seems like the script specified in my package.json manifest file is not being

After running npm start in the terminal, I encountered the following error message: PS C:\Users\finsa\OneDrive\Documents\UNI\Web Development\NS_Music_App> npm start > <a href="/cdn-cgi/l/email-protection" class= ...

Struggling to align images side by side using HTML and CSS along with figcaption and buttons

Adding buttons below images on my webpage is proving to be a bit challenging. I tried using the figcaption tag, but it resulted in the images stacking on top of each other instead of side by side. **My HTML:** <section class="mostpurch"> ...

What is the correct method for exporting an ES6 module function as a library to be utilized in a Node.js application?

Imagine having a node.js application that does not pass through webpack bundling: Node App const Html = require('./build/ssr-bundle.js'); let result = Html.ssrbundle.render(); console.log(result); Here is my ES6/JSX file, which undergoes web ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

Comparing the benefits of using npm cache clean versus npm cache verify

Can you explain the distinction between the two commands below? npm cache clean npm cache verify Additionally, what is the purpose of the force option? I am particularly interested in how these commands work in a Windows development environment. ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

Is it possible to emphasize a duration of 25 minutes on an analog clock by utilizing CSS gradients?

I am in the process of incorporating a countdown timer but with an analog clock rather than a digital one. My objective is to emphasize the next 25 minutes as a circle sector that commences from the minute hand on the clock. Here is what I have developed ...

PHP allows for creating dropdown lists where the values are dynamically dependent on the selection of another dropdown list within the same form

Is there a way for me to implement this solution? The values in the dropdownlist are based on another dropdownlist within the same form. For example, a form with dropdownlists for car names and models of that car, along with a search button. Please take no ...

Filtering rows of an HTML table that contain links in the `<href>` column data in real time

When using HTML and JavaScript, I have found a solution that works well for many of the columns I am working with. You can see the details on how to dynamically filter rows of an HTML table using JavaScript here. var filters=['hide_broj_pu',&apo ...

Using AXIOS POST to access a third-party API within a Firebase cloud function

When a user logs in for the first time on a website that uses some text and requires an API key, I am attempting to make an API call using Axios POST. I have initialized the necessary functions such as const functions = require('firebase-functions&apo ...

JavaScript and HTML - specify the location in the html document where the JavaScript script will be displayed

I'm a beginner when it comes to JavaScript. I am trying to make sure that my HTML page remains unchanged while JavaScript text is displayed in a specific location without refreshing the entire page. To trigger a JavaScript function via a button on a ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

Attempting to recreate the dynamic banner featured in the video

Looking to replicate a setup similar to what was demonstrated in the video. I have two div blocks - one with a random image and the other with a video, and I want them to be as flexible and identical as possible to the video layout. How should I go about a ...

Tips for organizing components in jQuery Mobile

Displaying a survey creation form: <!-- HTML structure --> <div data-role="page" data-theme="b"> <div data-role="header"> <h1> Create Survey </h1> </div> <div id="main" data ...

I am trying to create a login application using angular and ionic, but I am facing an issue with accessing the $stateProvider routing for the login page through the <ion-nav-view> element

index.html Description: The index.html file is the main file containing all the view pages. It includes HTML code for setting up the structure of the application. <!DOCTYPE html> <html ng-app="loginApp"> <head> <meta charset="u ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...