我是新手,我对官方网站的文档有点困惑...

我有控制器,在那里我可以调用服务方法:

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变量位置?我经常尝试,但是有些不好,需要帮助)

最佳答案

延迟注入角度:

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

关于javascript - promise 的 Angular 异步上传文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27704385/

10-09 12:46