@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');
})
}));
}
}
它仅适用于&#39; rand1&#39;字符串 - 同步, 但是observer.next(&#39; rand @ 2&#39;);
无法正常工作 - 异步。 如何让它发挥作用?
答案 0 :(得分:2)
您可以尝试以这种方式实现:
@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);
}
}
另请参阅 Plunker Example
答案 1 :(得分:1)
你在这里不需要AsyncPipe
@Pipe({
name: 'trans',
pure: false
})
export class RandomPipe implements PipeTransform {
constructor(private cdRef:ChangeDetectorRef) {
}
transform(value:string):any {
return new Observable<string>(observer=>{
observer.next('rand1');
setTimeout(()=>{
observer.next('rand@2');
})
}));
}
}
然后使用像
这样的异步管道{{someValue | trans | async }}