【问题标题】:Upload file to S3 but return observable将文件上传到 S3 但返回 observable
【发布时间】:2019-10-13 04:21:12
【问题描述】:

我如何确保下面的方法返回一个 observable?

  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);
  });

【问题讨论】:

    标签: angular amazon-s3 file-upload


    【解决方案1】:

    将结果/错误返回为 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> {
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多