我正在开发一个小型Web应用程序。 现在,我尝试实现文件上传功能。一切都很好。我可以上传,将其保存在服务器上,还可以接收文件路径。
我现在所困扰的是如何将路径传递回组件。
我尝试了几种解决方案,但不确定使用什么以及如何修改代码。
我应该使用异步,等待还是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);
感谢您的帮助:-)
最诚挚的问候
马库斯
答案 0 :(得分: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']));
};
组件:
something() {
this.projectsService.uploadImage(dataFile).subscribe(imgPath => {
console.log(imgPath);
}
}