【问题标题】:Angular refresh ngFor with async observable after POSTPOST后使用异步可观察的角度刷新ngFor
【发布时间】:2018-12-12 17:11:11
【问题描述】:

所以我像这样从 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,我用它来显示图像,那么在成功发布请求后如何将它放入我的observable currentGallery$ 中的数组'imagesID' >,所以 ngFor 可以在 POST 之后无需第二次 GET 就可以更新自己?

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

【问题讨论】:

    标签: angular post httpclient ngfor angular7


    【解决方案1】:

    您可以使用另一个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)
    } 
    

    Observable 数组相反,for 循环现在将遍历数组

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

    【讨论】:

    • 本来想这样的,但是在ngFor中不使用async也可以吗?我在互联网上阅读了一些文章,我应该对 http 请求使用异步。
    • 是的,完全没问题。 asyncngFor 不需要一起使用。 ngFor 可用于任何可迭代对象,而 async 管道用于可观察对象。它们是完全不同的两个。如果您直接迭代 Observable 数组,那么您只能将它们一起使用。 I have read some articles on the internet, that i should use async for http requests - 是的,因为 http 方法返回 Observable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    相关资源
    最近更新 更多