Sign up process through AngularJS

Looking to implement a straightforward registration process using AngularJS. Initially, I retrieve a user with a specific email and assign it to $scope.users. If the method "GetUserByEmail" returns multiple users, I attempt to display a message stating "User already exists". However, a challenge arises. The method GetUserByEmail is being bypassed. The program immediately jumps to the "if" condition and $scope.users remains empty for unknown reasons. Occasionally, after adding a user to the database, the method returns an array of objects and assigns them to $scope.users.

Below is my code featuring the CreateUser method:

var RegisterController = function ($scope, Api, $http) {

    $scope.users = {
    }

    $scope.CreateUser = function () {
        var user = {
            Password: $scope.password,
            Name: $scope.name,
            Surname: $scope.surname,
            Email: $scope.email,
            DateOfBirth: $scope.dateofBirth
        }

        Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).then(function (d) {
                $scope.users = d;
            }); 

        if ($scope.users.length > 0)
        {
            alert("User already exists!");
            $scope.users = {};
        }
        else
        {
            Api.PostUser("Users", "PostUser", user).then(function (d) {
                alert("Hello");
            });
        }


    };
}

RegisterController.$inject = ['$scope', 'Api', '$http'];

And the GetUserByEmail method:

this.GetUserByEmail = function (controllerName, methodName, email) {
        var promise = $http({
            method: 'GET',
            url: 'api/' + controllerName + '/' + methodName  + '?email=' + email,
            config: {
                params: {
                    "email": email
                }
            }
        })
        .then(function onSuccess(response) {
            return response.data;
        },
        function onError(response) {
            return response.statusText;
        });
        return promise;
    }

Answer №1

Give this code snippet a shot!

var RegisterController = function($scope, Api, $http) {

  $scope.users = {}

  $scope.CreateUser = function() {
    var user = {
      Password: $scope.password,
      Name: $scope.name,
      Surname: $scope.surname,
      Email: $scope.email,
      DateOfBirth: $scope.dateofBirth
    }

    Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).then(function(d) {
      $scope.users = d;
      if ($scope.users.length > 0) {
        alert("User already exists!");
        $scope.users = {};
      } else {
        Api.PostUser("Users", "PostUser", user, d).then(function(d) {
          alert("Welcome");
        });
      }
    });

  };
}

RegisterController.$inject = ['$scope', 'Api', '$http'];

Answer №2

If you utilize a success...error block in your request handling, even if the response is null, the request will be directed to the success block where you can validate your data. I believe this approach is appropriate for your situation.

var RegistrationController = function ($scope, Api, $http) {

    $scope.users = {
    }

    $scope.CreateUser = function () {
        var user = {
            Password: $scope.password,
            Name: $scope.name,
            Surname: $scope.surname,
            Email: $scope.email,
            DateOfBirth: $scope.dateofBirth
        }

        Api.GetUserByEmail("Users", "GetUserByEmail", $scope.email).success(function (response) {
                 if (response != null && response.length > 0)
        {
            alert("User already exists!");
            $scope.users = {};
        }
        else
        {
               Api.PostUser("Users", "PostUser", user)
                 .success(function (d) {
                  alert("Hello");
            }).error(function(e){
            console.log(e.message);
            });
        }
            }).error(function(error){
                console.log(error.message);
            }); 
    };
}

RegistrationController.$inject = ['$scope', 'Api', '$http'];

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

Leveraging the power of AngularJS to run JavaScript functions saved as strings

Is it possible to dynamically inject JavaScript code that is stored in a string into AngularJS controllers? var dynamicJS = "function DoSomething(value){var x = 1+1 return 2;}" I need to inject the above function dynamically into my AngularJS controller ...

The selected jQuery plugin is not functioning properly within CodeIgniter framework

I recently downloaded the jQuery Chosen plugin to use the simple "multiselect" version on my website. I followed all the necessary steps and even copied and pasted the code into CodeIgniter. Despite my experience with jQuery, I am facing an issue where the ...

Distinguishing a button based on its class

I am currently designing a website to showcase personalized store products. Each product info box includes a button, as shown in the screenshot below: https://i.sstatic.net/hiXiY.png Upon clicking on the "Options" button, users can view information about ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...

Create a log table specifically for tracking changes made to the drop-down menu

I need to create a Change log table that will track any changes made in the drop-down menu. For instance, I am working on a worksheet with a select menu called Results which includes options like Positive, Negative, Unknown. I want the system to log any ch ...

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

What sets apart using 'self.fn.apply(self, message)' from 'self.fn(message)', and what are the advantages of using the former method?

Whenever I come across code that looks like thisnewPromise.promiseDispatch.apply(newPromise, message), I can't help but wonder why they didn't simply use newPromise.promiseDispathch(message) ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Arrow function returns itself, not the function

While working with React, I've been using utility functions for managing API calls. I noticed that when the arrow function is no longer anonymous, it successfully returns a pending promise – which is exactly what I want. However, if the arrow functi ...

Having trouble sending a POST request with body parameters in Node.js? The error "undefined req.body.param" might be popping up when you're

I've encountered an issue with my server.js code: const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); var express = require('express') , http = requir ...

What is the reason behind the jQuery JSON parser requiring double escaping for backslashes?

I'm struggling to comprehend a strange aspect of the JSON data format. Here's the issue: I have a string with a Windows directory path, where backslashes are escaped. However, the jQuery JSON parser seems to require double escaping for some reas ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Exploring the DOM, store all anchor elements inside a <ul> tag with a specific ID in an array

I'm attempting to extract all the anchor tags from a list and store them in an array by traversing the DOM. So far, I have been successful in getting the list items and their inner HTML into an array, but I am facing difficulties in retrieving each LI ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Menu with dropdown navigation

Looking to create a dynamic and responsive navbar menu with items and subitems on my website. Bootstrap has proven to be challenging when adding submenus. Are there any tools, frameworks, codes or plugins that could assist me in achieving this? It's ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Charts created using Google VisualizationORThe visual representations

My chart is currently not displaying at 100% width as I intended. I would like the chart to span from the beginning to the end of the container. https://i.stack.imgur.com/Xjw6g.png Here's my code snippet: test.controller('testCtrl', [&apo ...

Triggering click events using requireJS and jQuery

I am currently utilizing requireJS in my project. Within my codebase, I have two essential files, one containing the main app configuration and functions: app/main.js define(["jquery", "jquery_migrate"], function() { return { bar: function() ...