在另一个函数更改后使用变量 - 未定义

时间:2016-08-10 17:39:36

标签: javascript angularjs

我想在执行uploadFiles函数后获取图像路径。这样,我将赋值给self.ProjectImagePath。但它不起作用,我认为它在函数调用后立即执行。有人可以帮忙吗?

        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;
              });
        }

执行后,图像上传到服务器但我无法获取其路径。 我正在使用AngularJS

1 个答案:

答案 0 :(得分:1)

在承诺(异步操作)完成之前,您遇到了调用代码的问题。

这应该做你需要的:

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);
}