Nathan Martins Nathan Martins - 3 months ago 7
AngularJS Question

Using a variable after it was changed by another function - getting undefined

I want to get the image path after the execution of the uploadFiles function. This way, I will have the value assigned to self.ProjectImagePath. But it is not working, I think it executes right after the function call. Anyone can help ?

self.submitProject = function(file) {
console.log("Submit Project \n");
uploadFiles.apply(this, arguments);
console.log(self.ProjectImagePath); ///ERROR HERE!!!! (UNDEFINED)
var data = JSON.stringify({
name: self.ProjectName,
room: self.room,
managers: self.Managers,
members: self.ProjectMembers,
image: self.ProjectImagePath
});
//console.log(data);
$http.post('/rooms/' + self.room + '/project', data).success(function(data) {
//$window.location.href = "/";
});
}

function uploadFiles(file) {
file.upload = Upload.upload({
url: 'projectImages/upload',
data: {
file: file
}
});

file.upload.then(function(response) {
$timeout(function() {
file.result = response.data;
self.ProjectImagePath = file.result;
});
}, function(response) {
if (response.status > 0)
self.errorMsg = response.status + ': ' + response.data;
});
}


After execution, the image is uploaded to the server but I cant get its path.
Im using AngularJS

Answer

You were having issues with calling code before the promise (asynchronous action) was finished.

This should do what you need:

self.submitProject = function(file) {
    console.log("Submit Project");

    function handleSuccess(response) {
        self.ProjectImagePath = file.result = response.data;

        // Should work correctly.
        console.log(self.ProjectImage);

        var data = JSON.stringify({
            name: self.ProjectName,
            room: self.room,
            managers: self.Managers,
            members: self.ProjectMembers,
            image: self.ProjectImagePath
        });

        $http.post('/rooms/' + self.room + '/project', data).success(function(data) {
            //$window.location.href = "/";
        });
    }

    function handleError(response) {
        if (response.status > 0)
            self.errorMsg = response.status + ': ' + response.data;
    }

    uploadFiles(file, handleSuccess, handleError);
};

function uploadFiles(file, successCallback, errorCallback) {
    file.upload = Upload.upload({
        url: 'projectImages/upload',
        data: {
            file: file
        }
    });

    file.upload.then(successCallback, errorCallback);
}
Comments