带有promise的角度异步上传文件

时间:2014-12-30 11:11:44

标签: javascript angularjs

我是棱角分明的新人,我从官方网站上的文档中有点困惑......

我有控制器,我有调用服务方法:

uploaderService.addImage(files);

和这样的服务:

.service('uploaderService', ['$http', 'settings', function ($http, settings) {

    var url = undefined;

    var addImage = function(files){
      var fd = new FormData();
      fd.append("file", files[0]);
      $http.post(settings.apiBaseUri + "/files", fd, 
        {
          withCredentials: true,
          headers: {'Content-Type': undefined },
          transformRequest: angular.identity
        })
        .success(function (data, status, headers, config) {         
            url = "temp.jpg";
        })
        .error(function (err, status) {
          console.log('operation failed, status: ' + status);
        });
    };

    var deleteImage = function(){      
    };   

    return {
      addImage: addImage,
      deleteImage: deleteImage
    }; 

如果完成后我怎么能等到发布数据请求,然后传入url变量位置?我尝试某某,但事情会变坏,需要帮助)

2 个答案:

答案 0 :(得分:2)

注入角度延迟:

.service('uploaderService', ['$http', '$q', 'settings', function ($http, $q, settings) {

然后在你的函数中使用它:

var addImage = function(files){

    var deferred = $q.defer();

    var fd = new FormData();
    fd.append("file", files[0]);
    $http.post(settings.apiBaseUri + "/files", fd, 
    {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    })
    .success(function (data, status, headers, config) {         
        url = "temp.jpg";
        deferred.resolve(data);
    })
    .error(function (err, status) {
        console.log('operation failed, status: ' + status);
        deferred.reject({msg: err});
    });

    return deferred.promise;
};

然后在你的控制器中:

uploaderService.addImage(files)
    .then(function(data){
        // success
        var url = data.url; // assuming the returned data of the ajax call contains an url variable
    }, function(error){
        // error
    }).finally(function(){
        // always
    });

答案 1 :(得分:1)

您需要返回$http.post(...)调用的结果,因为它返回一个Promise对象:

var addImage = function (files) {

    var fd = new FormData();
    fd.append("file", files[0]);

    return $http.post(settings.apiBaseUri + "/files", fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    })
    .success(function (data, status, headers, config) {
        return "temp.jpg";
    })
    .error(function (err, status) {
        return 'operation failed, status: ' + status;
    });
};

然后你会在控制器中使用它:

uploaderService.addImage(files).then(function(url) {
    console.log('uploaded', url);
}, function(message) {
    console.log(message);
});