Infinite loop when using function with http call in * ngFor with asynchronous tube

I call the function in the * ngFor expression:

@Component({
  selector: 'foo-view',
  template: '<div *ngFor="let foo of loadAll() | async"></div>'
})
export class FooComponent {

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}

When the code starts, it sends HTTP requests again and again in an endless loop.

Why? What can I do to avoid this?

PS I know a standard workaround, for example

@Component({
  selector: 'foo-view',
  template: '<div *ngFor="let foo of foos"></div>'
})
export class FooComponent implements OnInit {

  foos: Foo[] = [];

  ngOnInit() {
    loadAll().subscribe(foos => this.foos = foos);
  }

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}

but I'm looking for a way to reset the extra variable.

+4
source share
1 answer

. , Angular , , - , loadAll(), HTTP-. , , . . , , (, ).

- , , foos: Foo[].

, Observable, :

private cached;

ngOnInit() { 
  this.cached = this.http.get(`api/foos`)
    .map(response => response.json() as Foo[])
    .publishReplay(1)
    .refCount()
    .take(1);
}

:

<div *ngFor="let foo of cached | async"></div>

, , - , .

, RxJS 5.4.0 shareReplay(1) .publishReplay(1).refCount().

, changeDetection, . . ChangeDetectionStrategy,

+4

Source: https://habr.com/ru/post/1678466/


All Articles