【问题标题】:How to create new ngx-translate pipe (pure vs impure)如何创建新的 ngx-translate 管道(纯与不纯)
【发布时间】:2017-09-26 14:43:33
【问题描述】:

编辑: 我想基本扩展ngx-translate提供的管道,如下:

import { Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe } from "@ngx-translate/core";

@Pipe({
  name: 'msg'
})

export class MsgPipe extends TranslatePipe implements PipeTransform {
  transform(value: any, args: any[]): any {
    return super.transform(value, args)
  }
}

这仅在 pure 设置为 false 时有效,因此我认为 ngx-translate 的加载器尚未准备好。 有没有办法检查?这样我可以保持管道纯净并正常工作。

原帖(不相关):

我创建了一个简单地调用 translateService.instant 并返回结果的管道。

@Pipe({
  name: 'msg',
  pure: false
})
export class MsgPipe implements PipeTransform {

  constructor(private translateService: TranslateService) {}

  transform(value: any, args: any[]): any {
    console.log('checked. val = ', value)
    return this.translateService.instant(value, args);
  }
}

如果不将其标记为纯:false,管道只会返回值。有了它(我认为文件加载器已经完成)。

我的问题是每个管道被调用了大约 8 次,我可以通过更改检测来告诉管道在检索到值后停止检查吗?

【问题讨论】:

  • 只是一个简单的问题:为什么需要管道来管理翻译?它似乎并不实用,更像是一个不纯的管道。我相信他们使用纯管道来管理更新?您可以尝试更改使用管道的组件中的检测策略,但维护起来非常不切实际...
  • ngx-translate 提供管道,我想基本上扩展它,如我的编辑中所述

标签: angular typescript angular2-changedetection angular-pipe ngx-translate


【解决方案1】:

多次触发的问题是您想要一个纯管道的原因,因为它只会在输入引用更改时再次触发 (1)。即时翻译服务的问题在于,当您尝试加载某些内容时,翻译可能还不存在,因此纯管道无法帮助您。

对于 ngx-translate,已经有一个可以使用的管道,即翻译管道 (2)。

据我所知,您无法对管道进行任何操作以使其停止重新评估自身。为此,您可能希望将您的组件设置为 OnPush,以便它仅在其中一个输入发生变化时自行更新。

(1)https://angular.io/guide/pipes#pure-and-impure-pipes

(2)https://github.com/ngx-translate/core/blob/master/src/translate.pipe.ts

【讨论】:

  • 我尝试扩展管道,主要是因为它将用作查找常量的通用字符串。我尝试扩展它失败了,听起来我应该重新审视。我会告诉你的
  • 我尝试过简单地扩展 ngx-translate 提供的管道,但同样它只适用于不纯的管道。似乎超类已将不纯设置为 false,但它们以某种方式在内部管理更改检测
猜你喜欢
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
相关资源
最近更新 更多