【问题标题】:Angular make http get request then with data from get request make put requestAngular 发出 http get 请求,然后使用 get 请求中的数据发出 put 请求
【发布时间】:2020-03-19 21:27:08
【问题描述】:

我想在 AWS S3 上上传多张图片。

首先我在前端上传图像并向用户显示图像的预览,然后在 for 循环中我每次都运行函数 uploadFilesSimulator 来上传每张图像。

  prepareFilesList(files: Array<any>) {
  for (const item of files) {
  item.progress = 0;
  this.files.push(item);

  const reader = new FileReader();
  reader.onload = (filedata) => {
    item.url = reader.result + '';
  }

  reader.readAsDataURL(item);

  this.uploadFilesSimulator(item);
}

}

首先我向我的节点 js API 发出 get 请求。结果是key和url。 然后在获取 url 后,我运行 put request 将图像添加到该 url。

  uploadFilesSimulator(file: any) {
this.formService.getUploadUrl().subscribe(data => {
  let upload = this.formService.uploadImage(data.url, file).subscribe(data => {
    console.log(data)
  }, err => console.log(err));
});

这是可行的,但我想避免嵌套订阅。 我应该使用什么 rxjs 运算符?

【问题讨论】:

    标签: angular http rxjs


    【解决方案1】:

    三个运算符可以做到这一点:switchMapmergeMapconcatMap。更适合您的情况的是 mergeMap,尽管对于您的特定情况不会有任何区别,因为 this.formService.getUploadUrl() 只会发出一个事件。

    更多详情,我推荐这个优秀的网站:https://rxmarbles.com/

    你可以这样使用它:

    uploadFilesSimulator(file: any) {
        return this.formService.getUploadUrl().pipe(
            mergeMap(data => this.formService.uploadImage(data.url, file))
        );
    }
    

    【讨论】:

    • 由于某种原因它不会触发任何东西。什么也没发生,我尝试使用 switchmap margemap 和 concatmap。
    • getUploadUrl(): Observable { return this.http.get(${this.url}/upload); } uploadImage(url: string, file: any): Observable { let headers = new HttpHeaders({ 'Content-Type': file.type }); return this.http.put(url, file, {headers: headers }); }
    • 那是因为没有subscribe。只有订阅 observable 才会触发请求,但我将其从您的代码中删除,因为这是订阅组件(而不是服务)的好习惯
    • 感谢您的回答和这个伟大的网站!
    • 我明白了。再次感谢您。
    猜你喜欢
    • 2014-08-15
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2019-05-07
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多