如何解决如何使用angular将服务功能数据返回到组件?
我有一个具有s3存储桶上传功能的服务,并且能够将图像上传到s3。但是我无法将信息从服务层返回到组件。
您能帮我吗?
Service.ts:
async uploadFile(file,path): Promise<any> {
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: 'My Access Key',secretAccessKey: 'My Secret Key',region: 'eu-west-1'
}
);
const params = {
Bucket: 'sangram-adaptive',Key: path + '/' + file.name,Body: file
};
await bucket.upload(params,function (err,data) {
if (err) {
console.log('Error',err);
return err;
}
if (data) {
console.log('Successfully uploaded',data); // i am getting result after upload
this.fileData = data;
return this.fileData;
}
});
}
Component.ts
async upload() {
const file = this.selectedFiles.item(0);
let data = await this.s3FileuploadService.uploadFile(file,'tenant_files/' + Constants.TENANT + '/blogs');
console.log(data); // Here it's showing undefined
}
解决方法
考虑修改uploadFile
以返回Promise,如下所示:
uploadFile(file,path): Promise<any> {
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: 'My Access Key',secretAccessKey: 'My Secret Key',region: 'eu-west-1'
}
);
const params = {
Bucket: 'sangram-adaptive',Key: path + '/' + file.name,Body: file
};
return new Promise((resolve,reject) => {
bucket.upload(params,(err,data) => err ? reject(err) : resolve(data))
})
}
,
函数bucket.upload
返回哪种类型?
您也许不应该这样称呼它:
await bucket.upload(...)
万一它返回了诺言?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。