gpt4 book ai didi

javascript - 为什么异步管道不起作用?

转载 作者:行者123 更新时间:2023-11-29 19:09:45 25 4
gpt4 key购买 nike

@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');
})
}));
}
}

它仅适用于“rand1”字符串 - 同步,但是 observer.next('rand@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

关于javascript - 为什么异步管道不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com