angular - 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 即可更新自身?
或者也许还有其他更合适的方法?
解决方案
您可以使用另一个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>
推荐阅读
- electron - Electron NSIS 防止重新安装
- django - 在 views.py 中设置注册功能(尝试运行服务器时出现错误消息)
- angular - 重新安装后 TSC 挂起编译
- c++ - 无法使用在同一类中使用成员函数的线程进行编译
- python - 为什么 Spacy 的 NER 训练器返回令牌而不返回实体?
- r - 如何获得第一个和最后一个时间顺序之间的差异?
- angular - 如何允许某些带有角度的 URL 并从中收集数据
- javascript - html/javascript 中的画布线模糊
- swift - 如何在 Swift 中将此日期字符串格式“2018-03-30T14:36:10.093”格式化为日期
- html - 如何结合活动按钮和悬停?