Gleb Patcia Gleb Patcia - 2 months ago 7
Javascript Question

Why does not it work async pipe?

@Pipe({
name: 'trans',
pure: false
})
export class RandomPipe implements PipeTransform {
constructor(private cdRef:ChangeDetectorRef) {
}

transform(value:string):any {
return new AsyncPipe(this.cdRef).transform(new Observable<string>(observer=>{
observer.next('rand1');
setTimeout(()=>{
observer.next('rand@2');
})
}));
}
}


It works only 'rand1' string - sync,
but observer.next('rand@2');

not work - async.
how to make it work?

Answer

You can try to achive it this way:

@Pipe({
  name: 'someRand',
  pure: false
})
export class RandomPipe implements PipeTransform {
  constructor(private  cdRef:ChangeDetectorRef) {}

  pipe: AsyncPipe;
  obs: Observable<string>;

  transform(value:string):any {
    if (!this.pipe) {
      this.pipe = new AsyncPipe(this.cdRef);
      this.obs = new Observable<string>(observer=>{
        observer.next('rand1');
        setTimeout(()=>{
          observer.next('rand@2');
        }, 500)
      });
    }

    return this.pipe.transform(this.obs);
  }
}

See also Plunker Example