Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Endless loop in async pipe

Tags:

angular

pipe

I`m getting an endless loop when I try to bind a async function like this:

<tr *ngFor="let i of items">
     <td>{{myAsyncFunc(i) | async}}</td>
</tr>

this is the function:

private myAsyncFunc(i: string): Promise<string> {
        return Promise.resolve("some");
}

I'm doing something wrong? Or this is a bug?

like image 945
Matías González Avatar asked Dec 21 '16 14:12

Matías González


2 Answers

You're returning a new Promise from myAsyncFunc(i: string) on every call, that's why you get an "endless loop". Try returning the same Promise instance ;-)

The "endless loop" is actually not a traditional endless loop but rather a side-effect of async pipe triggering a change detection cycle when its input Promise resolves. On this new change detection cycle, angular will call myAsyncFunc(i: string) and get a new Promise to observe, which then resolves the whole thing starts again.

like image 187
Johannes Rudolph Avatar answered Oct 09 '22 08:10

Johannes Rudolph


If your async/observable requires you to pass a parameter (e.g., you are inside an ngFor loop) perhaps you can create a custom async pipe for that.

@Pipe({
  name: 'customPipe'
})
export class customPipe implements PipeTransform {

  constructor(private someService: SomeService) {}

  /**
   * 
   * @param id 
   */
  transform(id: number): Observable<boolean> {
    return this.someService.shouldShow(id);
  }

}

And in your template you can call your async pipe as:

<td>{{id | customPipe | async}}</td>
like image 45
jp6rt Avatar answered Oct 09 '22 06:10

jp6rt