如何使用 angular return 服务功能数据到组件?
how to return service function data to component using angular?
我有一个具有 s3 存储桶上传功能的服务,我可以将图像上传到 s3。但我无法 return 从服务层到组件的信息。
你能帮我解决这个问题吗?
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
}
bucket.upload
return函数是哪个类型的?
你不应该这样称呼它:
await bucket.upload(...)
如果它return是一个承诺?
考虑将 uploadFile
修改为 return 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))
})
}
我有一个具有 s3 存储桶上传功能的服务,我可以将图像上传到 s3。但我无法 return 从服务层到组件的信息。
你能帮我解决这个问题吗?
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
}
bucket.upload
return函数是哪个类型的?
你不应该这样称呼它:
await bucket.upload(...)
如果它return是一个承诺?
考虑将 uploadFile
修改为 return 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))
})
}