gpt4 book ai didi

angular - 上传文件到 S3 但返回 observable

转载 作者:行者123 更新时间:2023-12-05 03:01:00 25 4
gpt4 key购买 nike

我如何确保以下方法返回可观察值?

  uploadFile(file, filename) {
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: environment.awsAccessKeyId,
secretAccessKey: environment.awssecretAccessKey,
region: environment.awsRegion
}
);
const params = {
Bucket: environment.awsBucket,
Key: environment.awsKey + filename,
Body: file,
ACL: 'public-read',
ContentType: contentType
};

bucket.upload(params, function (err, data) {
if (err) {
this.logger.debug('There was an error uploading your file: ', err);
return null;
}
this.logger.debug('Successfully uploaded file.', data);
return data;
});
}

我想按如下方式从组件中调用它并捕获返回输出:

  this.ngxLoader.start();
this.uploadService.uploadFile(newFile, sermonName), ((data) => {
if (data) {
// this.sermon.id = data.id;
// this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
// this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
// this.update();
this.ngxLoader.stop();
}
}, error => {
this.ngxLoader.stop();
this.modalService.displayMessage('Oops!', error.message);
});

最佳答案

将结果/错误返回为 Observable


return Observable.create(observer => {
bucket.upload(params, function (err, data) {
if (err) {
this.logger.debug('There was an error uploading your file: ', err);
observer.error(err);
}
this.logger.debug('Successfully uploaded file.', data);
observer.next(data);
observer.complete();
});
});

更改以处理组件中的结果/错误


this.uploadService.uploadFile(newFile, sermonName)
.subscribe(
data => {
if (data) {
// this.sermon.id = data.id;
// this.logger.debug(`Posted file: ${JSON.stringify(data)}`);
// this.logger.debug(`Updating file id: ${JSON.stringify(this.sermon.id)}`);
// this.update();
this.ngxLoader.stop();
}
},
error => {
this.ngxLoader.stop();
this.modalService.displayMessage('Oops!', error.message);
});

当然我们需要导入下面的内容。

import { Observable } from 'rxjs';

还为函数添加显式返回以进行类型检查。

uploadFile(file, filename): Observable<any> {

关于angular - 上传文件到 S3 但返回 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328640/

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