Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

javascript - Angular Binding to a function on the view results to infinite calls to the data service

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...