Get value from within a function

3

I have a logic problem here, I think it must be a "dumb" thing on my part, like I have to get a value from within the function, and I'm not getting a return for being an http request. look:

$scope.postData = function(method, data, file){

    var uploadUrl = base_url+'main/upload/';

    fileUpload.uploadFileToUrl(file.file, uploadUrl, file.title);

    $http.get(base_url+'main/lastId/')
    .success(function (data) {
        lastId = data;
        return lastId; // <------ PRECISO DESSA VARIÁVEL
    });

    data.last_id = lastId; // <----- PARA USAR ELA AQUI

    $http.post(base_url+method+'/post/'+table, data)
    .success(function (data) {
        $scope.posts = data;
        $scope.exibirForm = 'listar';
        $scope.form = {};
        $scope.estadoBotao = "Adicionar";
    });
}

As you have seen, I need to get the lastId, to modify the data array to make a post with a link to the id of a file.

    
asked by anonymous 10.01.2017 / 14:27

2 answers

4

The link of AngularJS is asynchronous, so the variable will be undefined at this time.

One option is to use it in success , something like this:

$http.get(base_url + 'main/lastId/')
    .success(function(data) {
        lastId = data;
        facaAlgo(lastId); // irá passar o valor para a função
    });


function facaAlgo(lastId) {

    data.last_id = lastId; // Aqui poderá usar lastId, porquê terá sido resolvido pela Promise

    $http.post(base_url + method + '/post/' + table, data)
        .success(function(data) {
            $scope.posts = data;
            $scope.exibirForm = 'listar';
            $scope.form = {};
            $scope.estadoBotao = "Adicionar";
        });
}

What happens is that you are trying to use a value that does not yet exist, because http will not stop execution, it will run and move on to the next statement. The name to resolve this type of situation is callback .

    
10.01.2017 / 14:32
1

You can make a CALLBACK by passing the parameter to a new method, because when the AJAX result arrives, the function / method has probably already been executed.

Here is an example (not tested):

$scope.postData = function(method, data, file){
    var uploadUrl = base_url+'main/upload/';
    fileUpload.uploadFileToUrl(file.file, uploadUrl, file.title);
    $http.get(base_url+'main/lastId/')
    .success(function (data) {
        pegaRetorno(data); // <------ PRECISO DESSA VARIÁVEL
    });
}

function pegaRetorno(lastId){
    console.log(lastId);
    data.last_id = lastId; // <----- PARA USAR ELA AQUI  
    $http.post(base_url+method+'/post/'+table, data)
    .success(function (data) {
        $scope.posts = data;
        $scope.exibirForm = 'listar';
        $scope.form = {};
        $scope.estadoBotao = "Adicionar";
    });
    return valor;
}
    
10.01.2017 / 14:34