首页 > 解决方案 > POST后使用异步可观察的角度刷新ngFor

问题描述

所以我像这样从 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');
}        

我的帖子返回上传的 imageID,我用它来显示图像,那么在成功发布请求后如何将其放入我可观察的currentGallery$中的数组“imagesID”中,这样​​ ngFor 可以在 POST 之后无需第二次 GET 即可更新自身?

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

标签: angularposthttpclientngforangular7

解决方案


您可以使用另一个component property来存储您的array数据,而不是直接在一个上操作Observable,这样可以很容易地将新生成image id的推送到其中。

伪代码

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>

推荐阅读