Problem with returning an object from a factory in angular JS

1

Look, this is my code.

Traer:function($scope) {        

    $http({
        method:'GET',
        url:'http://localhost:8080/VENTAS2017/serviciosPHP/Categoria/GETCATEGORIA.PHP'
    }).then(function successCallBack(response){ 
        $scope.objeto = [];
        $scope.objeto = response.data;                                                
    },function errorCallBack(response){
        return response.data;
    });     
    return $scope.objeto;    
},

Now, the error is that something strange happens when I send the request the first time, it returns indefinitely but the second time the object returns.

    
asked by Jose Manuel 29.06.2017 в 04:21
source

1 answer

-1

What happens is that you are making an ajax request that by default is asynchronous. Therefore, the first time you execute the function, an ajax promise is requested

$http({
    method:'GET',
    url:'http://localhost:8080/VENTAS2017/serviciosPHP/Categoria/GETCATEGORIA.PHP'
})

and a return is executed on an object that has no value yet:

return $scope.objeto;

At an undetermined time between your first request and the next, the promise is resolved by giving value to the object

.then(function successCallBack(response){ 
    $scope.objeto = [];
    $scope.objeto = response.data;                                                
}

So, the next time you execute by doing the same sequence: 1. Make a promise ajax, 2. Make a return. The object you return already has value.

The solution is to execute the function in which you use the $scope.objet within the function then or wait for $ scope.object to be updated if you use it within your templates.

Traer:function($scope) {        

    $http({
        method:'GET',
        url:'http://localhost:8080/VENTAS2017/serviciosPHP/Categoria/GETCATEGORIA.PHP'
        }).then(function successCallBack(response){ 
            // Aquí ejecuta la función directamente sobre response.data en caso de ser necesario
            $scope.objeto = response.data;
    },function errorCallBack(response){
        // Haz algo con response.data. No lo devuelvas
        response.data;
    });     
    return $scope.objeto;    
},
    
answered by 29.06.2017 в 08:53