角度绑定到视图上的函数会导致对数据服务的无限调用 [英] Angular Binding to a function on the view results to infinite calls to the data service
问题描述
我试图将图像的src
属性绑定在如下所示的ngFor
指令中:
I'm trying to bind a src
attribute of images inside an ngFor
directive that looks like this:
<div *ngFor="imageId of imageIds">
<img [attr.src]="imageSrc(imageId)" alt="{{imageId}}">
</div>
组件内部的imageSrc
方法如下所示:
the imageSrc
method inside the component looks like this:
imageSrc(imageId: string){
var hostUrl = "http://192.168.0.101:3000/";
var imageUrl = hostUrl+"images/"+imageId;
var imgSrc = "";
this._imageService.getImage(imageId)
.subscribe(image => {
imgSrc = hostUrl + image.url
});
return imgSrc;
}
Injectable
ImageService
中的getImage
函数如下所示:
The getImage
function in the Injectable
ImageService
looks like this:
getImage(id: string) {
var _imageUrl = "http://192.168.0.101:3000/images/"+id;
return this.http.get(_imageUrl)
.map(res => <Image>res.json().data)
.catch(this.handleError)
}
问题是,只有两个imageIds
,*ngFor
指令按预期方式呈现了两个列表项(但没有显示图像),但是对数据服务的调用并未停止,它使两个图像结束并且直到应用程序崩溃为止,这似乎是一个无限循环.我在做什么错了?
The problem is, with only two imageIds
the *ngFor
directive renders the two list items as expected (but no images displayed) but the call to the data service doesn't stop, it gets the two images over and over on what appears to be an infinite loop until the application crashes. what I'm I doing wrong?
推荐答案
我不认为这与*ngFor
有关.如果从视图绑定到某个函数,则每次Angular运行更改检测时都会调用此函数,默认情况下,该事件发生在页面上发生的所有事件中.
I don't think this is related to *ngFor
. If you bind from the view to a function then this function is called every time Angular runs change detection which is by default on every event that happens on your page.
在devMode
中(与prodMode
相反),更改检测甚至针对每个事件运行两次.
In devMode
(in contrary to prodMode
) change detection even runs twice for each event.
将结果存储在一个属性中,然后绑定到该属性,或者,如果自上次调用以来输入参数(id:string
)从未更改,则至少在后续调用中从函数中返回缓存的结果.
Store the result in a property and bind to that property instead or at least return a cached result from your function on subsequent calls if the input parameter (id:string
) hasn't changed since the last call.
例如 https://stackoverflow.com/a/36291681/217408
这篇关于角度绑定到视图上的函数会导致对数据服务的无限调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!