我如何确保以下方法返回可观察的结果?
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);
});
答案 0 :(得分:2)
进行更改以将结果/错误返回为“可观察”
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> {