gpt4 book ai didi

angular - 使用不同名称的管道

转载 作者:行者123 更新时间:2023-12-02 16:13:24 25 4
gpt4 key购买 nike

我在 Angular 6 应用程序中使用 ngx-translate 国际化库。现在我的一个模板中的翻译是这样完成的:

<span>{{ 'HELLO' | translate:param }}</span>

但是,如果我能这样就太好了:

<span>{{ 'HELLO' | i18n:param }}</span>

我所要做的就是以某种方式为管道指定一个别名,但我不知道如何实现这一点。我开始写一些类似的东西......

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

@Pipe({ name: 'i18n' })
export class I18nPipe implements PipeTransform {

constructor(private i18n: TranslateService) { }

transform(key: string, ...args: any[]): any {
this.i18n.get(key).subscribe((res: string) => {
return res || key;
});
}

// How to return if async? How to process args?

}

但是我是否应该这样编码,或者 Angular 中是否有一种简单的通用方法来别名管道?

我尝试的另一种方法:

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

@Pipe({ name: 'i18n' })
export class I18nPipe extends TranslatePipe implements PipeTransform {

transform(key: string, args?: any): any {
return super.transform(key, args);
}

}

这给了我一个错误:

ERROR TypeError: Cannot read property 'get' of undefined
at I18nPipe.updateValue (ngx-translate-core.js:1058)
at I18nPipe.transform (ngx-translate-core.js:1097)
at I18nPipe.transform (i18n.pipe.ts:8)

最佳答案

你可以只包住原来的 pipe

@Pipe({name: 'i18n'})
export class I18nPipe implements PipeTransform {
constructor(private translatePipe: TranslatePipe) {
}

transform(query: string, ...args: any[]) {
return this.translatePipe.transform(query, args);
}
}

关于angular - 使用不同名称的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470434/

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