A
A
Abc Edc2016-10-09 14:01:12
JavaScript
Abc Edc, 2016-10-09 14:01:12

How to make pipe work asynchronously without always specifying |async in templates in angular 2?

@Pipe({
  name: 'someRand',
  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('[email protected]');
      })
    }));
  }
}

How to force the pipe to output a string inside the timeout, because in such an implementation only synchronous output works - 'rand1'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-10-09
@gleber1

I think it's possible 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('[email protected]');
        }, 600)
      });
    }
  
    return this.pipe.transform(this.obs);
  }
}

600 added just for the sake of asynchrony)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question