我有一个 img src,看起来像这样:
<img [src]="currentImg" />
它遍历 JSON 并获取图像 url。
我在图像下方有一个按钮,可以直接刷新 JSON feed。
<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: "图像.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”管道而不是销毁订阅。 这是一个更好的方法,请尽可能尝试使用它。
我不会使用任何 ngIf。每次用户生成新图像时图像都会跳转。
希望这有帮助!
关于javascript - 从刷新的 JSON 更新 img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60700864/