Service AngularJS returns me Undefined in return!

0

I have tried every possible way to change the order of the code, but the same thing happens again and again, I'm getting frustrated, I would like to know why it returns undefined so I do not run into this problem again, I've done the tests to know that the next function does not return empty, but still it does. I show my code below: Next I define the application:

var app = angular.module('sonidoambiental', ['ngRoute']).
        config(['$routeProvider', function($routeProvider) {
                $routeProvider.when('/', { templateUrl: 'inicio.html', abstract: true, controller: "InicioController"}).
                when('/listado', {templateUrl: 'listado.html', controller: "ListadoController"})./*
      when('/agregar', {templateUrl: 'plantillas/agregar.html', controller: ControladorAgregar}).*/
        otherwise({redirectTo: '/'});
    }]);

The service that returns undefinited is as follows:

app.factory('comunicacion', function() {
        return {        
        obtenerstring: function(pregunta){            
            var retorna;
            $.ajax({
                url: '/json/' + encodeURI(pregunta),
                dataType: 'json',
                method: 'get',
                success: function(datos) {
                    /* Si todo ha ido bien mostramos una alerta con el contenido */
                    if (typeof datos.error !== 'undefined' && datos.error === false) {
                        console.log(datos.mensaje);
                        retorna= datos.mensaje;                        
                        //alert("Mensaje recibido: " + datos.mensaje);
                    } else {
                        retorna = null;                        
                    }
                }
            });
            return retorna;
        }
        }        
    });

And I call it in the following way: app.controller ("StartController", ['$ scope', 'communication', function ($ scope, $ interval, communication) {
    $ scope.primerinicio = function () {
        if (comunicacion.obtenerstring ('sinusuarios') === '') {             titulodeformulario="No user created please enter the corresponding data";
                        createuser = true;                         botoningresar="Create user";
                        $ scope.titleofform = titleformform;                         $ scope.botoningresar = botoningresar;                         $ scope.crearusuario = crearusuario;                         $ scope. $ apply ();         }

Well, if someone clarifies this scenario would be very nice help, In the part that says Console.log (data.message); it returns the real value and not undefinited, so I assure you that it is not a function problem.

    
asked by Bernardo Harreguy 09.02.2018 в 18:24
source

1 answer

2

The problem lies in the implementation of the factory.

app.factory('comunicacion', function() {
    return {        
    obtenerstring: function(pregunta){            
        var retorna;
        $.ajax({
            url: '/json/' + encodeURI(pregunta),
            dataType: 'json',
            method: 'get',
            success: function(datos) {
                /* Si todo ha ido bien mostramos una alerta con el contenido */
                if (typeof datos.error !== 'undefined' && datos.error === false) {
                    console.log(datos.mensaje);
                    retorna= datos.mensaje;                        
                    //alert("Mensaje recibido: " + datos.mensaje);
                } else {
                    retorna = null;                        
                }
            }
        });
        return retorna;
    }
    }        
});

You have a variable declaration

var retorna;

Then an invocation to an asynchronous jQuery method.

$.ajax(...)

To finally return the variable declared previously

return retorna;

The above would only work if the invocation were synchronous. But more importantly, you should use angular components such as the $http service and return a promise as a result.

Service Docs: link $ http

    
answered by 09.02.2018 / 19:25
source