将http.post后的数据传递给组件

问题描述 投票:0回答:1

我正在做一个小型的web应用程序,现在我试图实现一个文件上传功能。一切都很顺利。我可以上传,保存在服务器上,也可以接收文件路径。

我现在苦恼的是,如何将路径传回组件。

我尝试了几种解决方案,但我不知道该用什么,也不知道如何修改代码。

我应该使用async, await或者Eventemitter,Observable等?

如何正确地使用它们,我收到组件中的路径,我知道我必须做等待服务函数做完成。

服务中的函数

  // Images hochladen
  uploadImage(postData: FormData): string{
    this.http.post('https://10.0.0.3:3000/api/upload/image', postData)
    .subscribe((responseData) => {
      this.imgPath = responseData['path'];
      console.log(this.imgPath)
    });
    return this.imgPath;
  };

而在组件中

const imgPath = this.projectsService.uploadImage(dataFile);
console.log(imgPath);

谢谢你的帮助:-)

最诚挚的问候

马库斯

angular http observable form-data
1个回答
0
投票

两个主要的选择。

使用承诺。

服务:

async uploadImage(postData: FormData): Promise<string> {
    const promise = this.http.post('https://10.0.0.3:3000/api/upload/image', postData).toPromise();
    return (await promise)['path'];
  };

组件:

async something() {
  const imgPath = await this.projectsService.uploadImage(dataFile);
  console.log(imgPath);
}

使用观测值。

服务:

uploadImage(postData: FormData): Observable<string> {
    return this.http.post('https://10.0.0.3:3000/api/upload/image', postData)
               .pipe(last(),map(r => r['path']));
  };

Component:

something() {
  this.projectsService.uploadImage(dataFile).subscribe(imgPath => {
     console.log(imgPath);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.