Как я могу гарантировать, что следующий метод возвращает наблюдаемое?
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> {