刷新自身的 Angular 纯管道

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月14日 06:52:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定