gpt4 book ai didi

angular - 创建本身异步的自定义管道

转载 作者:太空狗 更新时间:2023-10-29 17:10:17 25 4
gpt4 key购买 nike

我创建了一个自定义管道,可以从 API 中检索文本内容,如下所示:

@Pipe({ name: 'apiText' })
export class ApiTextPipe implements PipeTransform {
constructor(private myApiService: MyApiService) {
}

transform(key: string): Observable<string> {
return this.myApiService.getText(key);
}
}

我必须像这样使用它:

<strong>{{'some-key' | apiText | async}}</strong>

但实际上我总是想要组合apiTextasync 管道。我更愿意这样写:

<strong>{{'some-key' | apiTextAsync}}</strong>

我能以某种方式做到这一点,并通过组合两个管道使事情变得更干吗?


更新 1:我有 opened a GitHub issue作为为此解决方案的功能请求。

更新 2:问题已关闭,因为 the async pipe "is not special" and "nothing prevents you from writing one that is similar 🤷‍♂️

最佳答案

一些评论者指出(这是理所当然的)这违反了 SRP 并且可能会损害可读性。但即使这会让我重新考虑我是否想要这个,我仍然肯定想知道如果你想要它该怎么做。我找到了两个解决方案(再次在评论者的帮助下)。

组成(不推荐)

创建您自己的内部 AsyncPipe 并使用它。这是一个应该有效的基本设置:

@Pipe({ name: 'apiText', pure: false })
export class ApiTextPipe implements PipeTransform, OnDestroy {
private asyncPipe: AsyncPipe;

constructor(private myApiService: MyApiService, private injector: Injector) {
this.asyncPipe = new AsyncPipe(injector.get(ChangeDetectorRef));
}

ngOnDestroy() {
this.asyncPipe.ngOnDestroy();
}

transform(key: string): string {
return this.asyncPipe.transform(this.myApiService.getText(key));
}
}

除了上述缺点(评论者指出)之外,我还看到了其他问题:

  • 如果 AsyncPipe 发生变化,例如它开始实现OnInit,然后我们自己的管道也需要改变。你可能会错过这个。我们的管道实现以这种方式耦合到 AsyncPipe 并不好。

  • 我似乎无法注入(inject) AsyncPipe,因为它依赖于特殊的 ChangeDetectorRef,所以我使用了 this suggested approach直接从喷油器询问。 (可能有更好的方法来做到这一点,但我现在不进一步挖掘......)

继承(不推荐)

您也可以尝试在您自己的管道中extends AsyncPipe,但这条路线包含更笨拙的代码,将您的管道与异步管道紧密耦合。我尝试这种方法时遇到的一些问题:

  • 您再次需要一个 ChangeDetectorRef 传递给 super(...) 调用
  • 您需要与 AsyncPipe 中的 transform 方法的签名紧密耦合
  • transform 变得 super 复杂,因为它不再只需要一个字符串(见上一点)
  • 我不知道这是否正确地使 Angular 调用父类(super class)的 ngOnDestroy 方法

还有其他我忘了的。我觉得代码太恶心了,甚至共享它似乎也不明智。

复制源(不推荐?)

正如其中一位评论者所建议的那样,the source for AsyncPipe开了。所以你可以利用它并从中构建你自己的管道。

在我看来,这不是一个明智的决定,我建议反对,但是it is the solution recommended by the Angular team on GitHub .

坚持使用双管道(唯一合适的选择?)

这样做 {{'some-key' | api文本 | async}} 并且总是使用两个管道,这似乎是目前唯一比较合理的选择。

关于angular - 创建本身异步的自定义管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51481630/

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