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

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

问题描述

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

<img [attr.src]="imageSrc(imageId)" alt="{{imageId}}">

组件内的 imageSrc 方法如下所示:

imageSrc(imageId: string){var hostUrl = "http://192.168.0.101:3000/";var imageUrl = hostUrl+"images/"+imageId;var imgSrc = "";this._imageService.getImage(imageId).订阅(图像=> {imgSrc = hostUrl + image.url});返回 imgSrc;}

Injectable ImageService 中的 getImage 函数如下所示:

getImage(id: string) {var _imageUrl = "http://192.168.0.101:3000/images/"+id;返回 this.http.get(_imageUrl).map(res => <Image>res.json().data).catch(this.handleError)}

问题是,只有两个 imageIds*ngFor 指令按预期呈现两个列表项(但不显示图像),但对数据服务的调用没有不会停止,它会一遍又一遍地获取两个图像,这似乎是一个无限循环,直到应用程序崩溃.我做错了什么?

解决方案

我认为这与 *ngFor 无关.如果您从视图绑定到一个函数,那么每次 Angular 运行更改检测时都会调用此函数,默认情况下,在页面上发生的每个事件上都会调用此函数.

devMode 中(与 prodMode 相反)变化检测甚至对每个事件运行两次.

将结果存储在一个属性中并改为绑定到该属性,或者如果输入参数 (id:string) 自调用以来没有更改,则至少在后续调用中从您的函数返回一个缓存结果最后一次通话.

例如https://stackoverflow.com/a/36291681/217408

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>

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

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

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?

解决方案

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 (in contrary to prodMode) change detection even runs twice for each event.

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.

For example like shown in https://stackoverflow.com/a/36291681/217408

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

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