I can not launch an "existing mail" alert


I have taken back the code that another developer left unfinished and I have some problems when I want to register a new user.

In the validation of the existing mail, I can not overwrite the previous record, but I can not launch an "existing user" alert and it tells me that the registration has been successful.

My development is a hybrid mobile app with IONIC 1 and AngularJS.

The code:

//estas validaciones funcionan excelente
$scope.doLogin = function () {
        console.log('Doing login', $scope.loginData);

        var errors = 0;

        $scope.errorPassword = ''
        $scope.errorPassword2 = ''
        $scope.errorRpassword = ''
        $scope.errorEmail = '';
        $scope.errorEmail2 = '';
        $scope.errorEmail3 = '';

            document.getElementById('email').style.boxShadow = 'inset 0 0 10px #e42112';
            $scope.errorEmail = '* El email no puede estar vacío<br>';
        } else if(!$scope.loginData.email.match(/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$/)) {
            $scope.errorEmail2 = '* El formato del email es inválido<br>';
            document.getElementById('email').style.boxShadow = 'inset 0 0 10px #e42112';

        } else if($scope.loginData.email !== $scope.loginData.r_email) {
            $scope.errorEmail3 = '*Los email no coinciden<br>';
            document.getElementById('email').style.boxShadow = 'inset 0 0 10px #e42112';
            document.getElementById('r_email').style.boxShadow = 'inset 0 0 10px #e42112';
            document.getElementById('email').style.boxShadow = 'none';
            document.getElementById('r_email').style.boxShadow = 'none';
  //hasta aquí todo perfecto
  // esta es la alerta que no me envía:
  $http.get($scope.url + "api/validarEmailMob",{ 
          "email": $scope.loginData.email,
        }, { headers: { 'Content-Type': 'application/json' } }).then(function (res){
        }, function(res){
                      title: 'Alerta',
                      template: 'Usuario ya existe !'


        if (errors == 0) {
          $http.post($scope.url + "/registrar/registraPaciente",
                "name": $scope.loginData.nombre,
                "aPaterno": $scope.loginData.a_paterno,
                "aMaterno": $scope.loginData.a_materno,
                "email": $scope.loginData.email,
                "password": $scope.loginData.password,
                "password_confirmation": $scope.loginData.r_password,
                "rfc": $scope.loginData.rfc,
                "role": "paciente"
            }, { headers: { 'Content-Type': 'application/json' } }).then(function (respuesta) {
                if (respuesta.data.mensaje) {
                    $scope.respuesta = respuesta.data.mensaje;
                } else {
                	$timeout(function () {
                	}, 1000);

                      title: 'Registro',
                      template: 'Usuario registrado exitosamente'

<ion-modal-view class="registro login" style="background:url(img/background.jpg);background-size:cover;">
    	<section class="top" style="background:none!important;">
        	<img src="img/logo-grande.png" alt="Ángeles hospitales"/>
            <!--a href="#"><i class="ion-ios-telephone-outline"></i></a-->
            <a href="#" ng-click="closeModal()"><i class="ion-android-close"></i></a>
    	<h1 class="titulo_login">Registro</h1>
        <p class="light" style="text-align:center;" ng-if="registro_error">{{registro_error}}</p>
        <form ng-submit="doLogin()">
            <div class="list-inset">
                <label class="item item-input" id="nombre">
                    <input type="text" pattern="[a-zA-Z-ñÑ-áÁ-éÉ-óÓ-úÚ\s]*" placeholder="Nombre" ng-model="loginData.nombre" autofocus>
                <label class="item item-input" id="a_paterno">
                    <input type="text" pattern="[a-zA-Z-ñÑ-áÁ-éÉ-óÓ-úÚ\s]*" placeholder="Apellido Paterno" ng-model="loginData.a_paterno" >
                <label class="item item-input" id="a_materno">
                    <input type="text" pattern="[a-zA-Z-ñÑ-áÁ-éÉ-óÓ-úÚ\s]*" placeholder="Apellido Materno" ng-model="loginData.a_materno">
                <label class="item item-input" id="edad">
                    <input type="text" class="form-control" placeholder="Fecha de Nacimiento" onfocus="(this.type='date')" ng-model="loginData.edad" style="
                    font-size: 1.2em;
                    padding-top: 1px;
                    " >
                <label class="item item-input" id="rfc">
                    <input type="text" ng-model="loginData.rfc" placeholder="RFC (Opcional)">
                <label class="item item-input" id="email">
                    <input type="email" ng-model="loginData.email" placeholder="Email">
                <label class="item item-input" id="r_email">
                    <input type="email" ng-model="loginData.r_email" placeholder="Repetir Email">
                <label class="item item-input" id="password">
                    <input type="password" ng-model="loginData.password" placeholder="Contraseña (min 7)" ng-minlength="7">
                <label class="item item-input" id="r_password">
                    <input type="password" ng-model="loginData.r_password" placeholder="Repetir Contraseña (min 7)" ng-minlength="7">
                <label class="item-checkbox-angeles">
                    <input type="checkbox" ng-model="loginData.terminos" checked="false"><span></span>
                <a href="#" ng-controller="terminos" ng-click="openModal()">He leído y acepto los términos y condiciones.</a>
                <button class="button button-block button-assertive" ng-disabled="(!loginData.terminos)" type="submit">Registrarse</button>
asked by Aaron Cortés 22.09.2016 в 06:18

1 answer


The main problem you have is that the GET to validate the user and the POST to create a new one are running in parallel.

Now you do ..

$http.get($scope.url + "api/validarEmailMob", ...
   // aqui en el handler de error estableces ++error

if (error == 0) {
    // creas el nuevo usuario.

Here two things happen:

1- These two instructions are executed in sequence, but the error handler is executed as a callback when the request ends. It is the asynchronic nature of the I / O in javascript.

2- The error handler (where it puts ++error ) is only invoked if there is an error in the request (I mean: 404 not found, 500 server error, connection timeout, etc). It is not invoked if the request returns a valid value, in that case the handler of success is invoked, the first function that you declare, which is empty.

How to fix it:

Using the Promises (or Promises) one behind the other and looking for a way to validate the email well. For that you have to know the possible answer of the server if the mail exists.

This would be chained the results, so that they are executed in series, that is to say the record when the validation ends.

Assuming that endpoint api/validarEmailMob returns { existe: true } when the email is already registered, and false when not, you can do the following ones.

$http.get($scope.url + "api/validarEmailMob", { .... })
     .then(function (resp) {
       if (resp.data.existe) {
          // Alerta el usuario existe
       } else {
          return $http.post(...
             // creas el nuevo usuario.
     }).catch(function (resp) {
       // sucedio un error con alguna de las solicitudes, entoces 
       // informas al usuario que debe volver a intentar mas tarde. o similar.
answered by 22.09.2016 / 18:25