Angular 在 POST 之后使用异步可观察刷新 ngFor

Angular refresh ngFor with async observable after POST

所以我正在像这样显示来自 HTTP GET 的图像

<div *ngFor="let item of (currentGallery$ | async)?.imagesID" class="col-4">
     <img class="img-fluid" src="url/{{item}}/thumb">
</div>

但是在将图片上传到服务器然后在图库中显示新图片时出现问题。

到目前为止,我得到的唯一解决方案是在上传后 POST,触发新的 GET 请求,但这似乎很糟糕。

this.http.post(url, formImageData).subscribe(data => {
    this.currentGallery$ = this.http.get<GalleryData>('url');
}        

我的post return上传的imageID,我用来显示图片的,所以post请求成功后如何把它放入数组'imagesID' 在我的可观察 currentGallery$ 中,所以 ngFor 可以在 POST 之后无需第二次 GET 就可以更新自身?

或者还有其他更合适的方法?

你可以利用另一个component property来存储你的array数据,而不是直接在Observable上操作,这样可以很容易地推送新生成的[=16] =] 在里面。

伪代码

public currentGallery = [];

ngOnInit(){
   // This should ideally happen from the service and map the data back to component
    this.http.get(url).subscribe(data => {
         this.currentGallery = data['imagesID'];
   });   
}

并且一旦您收到来自 POST 请求的响应,您就可以直接将数据(新 ID)推送到该数组

this.http.post(url, formImageData).subscribe(data => {
    this.currentGallery.push(data.id)
} 

并且 for 循环现在将遍历数组而不是 Observable 数组

<div *ngFor="let item of currentGallery" class="col-4">
     <img class="img-fluid" src="url/{{item}}/thumb">
</div>