英文:
Make Angular Pure Pipe refresh itself
问题
以下是要翻译的内容:
纯管道是否可以在内部刷新其返回值?
我想让我的纯管道拥有内部订阅并定期刷新返回值。不幸的是,据我了解,只有父组件可以调用管道的transform方法(当输入发生变化时),因此管道无法自行刷新。
https://stackblitz.com/edit/angular-qx2jzq?file=src/main.ts
@Pipe({ name: 'purePipe', pure: true })
export class Pure {
value = 0;
constructor(service: Service, cd: ChangeDetectorRef) {
service.subject.subscribe((val) => {
this.value = val; // 我想要刷新返回值
cd.detectChanges();
});
}
transform(input: number) {
return this.value; // 由于我返回的是值而不是引用,所以无法刷新
// transform() 仅在输入发生更改时调用,
// 因此无法从内部调用它
}
}
英文:
Is it possible for pure pipe to refresh it's returned value internally?
I'd like my pure pipe to have an internal subscription and refresh returned value periodically. Unluckily, as I understand, only parent component can call transform method of pipe (when input changes), so pipe cannot refresh itself.
https://stackblitz.com/edit/angular-qx2jzq?file=src/main.ts
@Pipe({ name: 'purePipe', pure: true})
export class Pure {
value = 0;
constructor(service: Service, cd: ChangeDetectorRef) {
service.subject.subscribe((val) => {
this.value = val; // I'd like to refresh returned value
cd.detectChanges();
});
}
transform(input: number) {
return this.value; // Since I return by value, not reference, I can't refresh
// transform() is called only when input changes,
// so I can't call it from inside
}
}
答案1
得分: 2
你无法做你正在寻找的事情。
在ChangeDetection周期中调用Pipe.transform
。
通过将你的管道设置为pure: true
,CD不会调用你的管道,除非它的输入值发生变化(这在这种情况下并不适用)。
由于你在管道内缓存了值,你可以使你的管道不纯,成本将是可忽略的。这正是AsyncPipe
的工作原理。它是不纯的并且缓存了订阅的值。
英文:
You can't do what you're looking for.
The Pipe.transform
is called during the ChangeDetection cycle.
By making your pipe pure: true
, CD won't call your pipe unless its input value changes. (which isn't the case here).
Since you're caching your value within the pipe, you can make your pipe unpure, the cost will be negligeable. That's exactly how the AsyncPipe
works. It is unpure and caches the subscribes values.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论