从回调获取数据,然后将其保存在AngularJS变量 [英] Get Data from a callback and save it to a variable in AngularJS

查看:403
本文介绍了从回调获取数据,然后将其保存在AngularJS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的服务 code,这是保存图像 -

Following is my service code, which is saving an image -

angular.module("app").service('fileUpload', ['$http', function ($http) {
    return {
      uploadFileToUrl: function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(response){
          return response;
        })
        .error(function(){
        });        
      }
    }

}]);

在我的控制器我有以下code -

In my Controller I am having the following code -

// Code for Image handling - START
if ($scope.myFile) {
    var file = $scope.myFile;
    console.log('file is ' + JSON.stringify(file));
    var uploadUrl = "/api/fileUpload";
    console.log("__FILE UPLOAD INFO__CHECK");
    console.log(fileUpload.uploadFileToUrl(file, uploadUrl));

}
// Code for Image handling - END

我期待CONSOLE.LOG后的console.log返回的数据(__文件上传INFO__CHECK); 但在控制台的未定义

虽然我正在从AJAX请求控制台成功响应 -

Though I am getting the success response in the console from the AJAX request -

{
    "success": true,
    "old_path": "/tmp/ddde0cf3b8a8e4fa83a92b361e814394",
    "new_path": "/MYPROJECT_PATH/uploads/ddde0cf3b8a8e4fa83a92b361e814394.png",
    "save_image_name": "ddde0cf3b8a8e4fa83a92b361e814394.png"
}

让我知道我做错了这里的回调?

Let me know what I am doing wrong with the callback here ?

推荐答案

这是异步,所以你应该有一个回调函数做到这一点。

It's async so you should do it with a callback function.

angular.module("app").service('fileUpload', ['$http', function ($http) {
    return {
      uploadFileToUrl: function(file, uploadUrl, successCb, errorCb){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(response){
            if(successCb){
                successCb(response);
            }
        })
        .error(function(){
            if(errorCb){
                errorCb();
            }
        });        
      }
    }

}]);

这篇关于从回调获取数据,然后将其保存在AngularJS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆