gpt4 book ai didi

javascript - 带有 promise 的 Angular 异步上传文件

转载 作者:行者123 更新时间:2023-11-30 12:30:59 24 4
gpt4 key购买 nike

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

我有 Controller ,我有调用服务方法:

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 变量位置?我尝试了某某,但有些事情会变坏,需要帮助)

最佳答案

注入(inject) Angular 延迟:

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

然后在你的 Controller 中:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com