[英]How to update src of a img from javascript in a play framework project?
[英]Update img src from a refreshed JSON
我有一個 img src,它看起來像這樣:
<img [src]="currentImg" />
它遍歷 JSON 並獲取圖像 url。
我在圖像下方有一個按鈕,可以直接刷新 JSON 提要。
<a (click)="refreshFeed(url)">Refresh feed</a>
refreshFeed(url) {
this.subscriptions.add(
this.jsonService.getJson().subscribe(() => {
this.currentImg = url.properties.img;
return this.currentImg;
})
)
}
但是,雖然我可以看到它正在獲取新的 json,但它似乎根本沒有更新圖像 url 並更改它的源,而且圖像 url 在 json 中將始終是相同的名稱 (img: "image.jpeg ”)
任何幫助表示贊賞。
首先, subscribe 是一個 void 函數,它沒有返回值的意義。 其次,您似乎在組件樹的某處使用了不同的變更檢測策略。
嘗試執行以下操作,如果有效,那么您肯定會使用 onPush 策略。
constructor(
...,
private cd: ChangeDetectorRef,
...
) {
...
}
refreshFeed(url: string) {
this.jsonService.getJson()
.pipe(take(1))
.subscribe(data => {
this.currentImg = data.properties.img;
this.cd.detectChanges();
})
}
我使用了 Rxjs “take” 管道而不是銷毀訂閱。 這是一個更好的方法,請嘗試在可能的地方使用它。
我不會使用任何 ngIfs。 每次用戶生成新圖像時,圖像都會跳轉。
希望這可以幫助!
像這樣嘗試:
.html
<img [src]="currentImg" *ngIf="showImage"/>
.ts
showImage:boolean
refreshFeed(url) {
this.showImage = false;
this.subscriptions.add(
this.jsonService.getJson().subscribe(() => {
this.currentImg = url.properties.img;
this.showImage = true;
return this.currentImg;
})
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.