Angular 2绑定到视图上的函数会导致对数据服务的无限调用 [英] Angular 2 Binding to a function on the view results to infinite calls to the data service

查看:242
本文介绍了Angular 2绑定到视图上的函数会导致对数据服务的无限调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ngFor 指令中绑定图像的 src 属性,如下所示:

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;
}

getImage 函数在可注射 ImageService 看起来像这样:

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.

In 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

这篇关于Angular 2绑定到视图上的函数会导致对数据服务的无限调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆