首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何扩展ngx-translate管道

如何扩展ngx-translate管道
EN

Stack Overflow用户
提问于 2017-09-27 00:39:45
回答 5查看 4.8K关注 0票数 3

我想扩展ngx-translate的管道,使其在我的应用程序中具有潜在的多用途。

我的烟斗:

代码语言:javascript
复制
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)
  }
}

为了等待相关的翻译模块加载,我使用了Angular的APP_INITIALIZER:

app.module:

代码语言:javascript
复制
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { appRoutes } from './app.routes';
import { AppComponent } from './root/app.component';
import { PageNotFoundComponent } from './shared/components/page-not-found/page-not-found.component';
import { HomePageComponent } from './shared/components/home-page/home-page.component';
import { MsgPipe } from './shared/pipes/msg.pipe';
import { ChangeDetectorRef } from '@angular/core';
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { Injector, APP_INITIALIZER } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { LOCATION_INITIALIZED } from '@angular/common';

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
}


export function appInitializerFactory(translate: TranslateService, injector: Injector) {
    return () => new Promise<any>((resolve: any) => {
        const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
        locationInitialized.then(() => {
            const langToSet = 'en'
              translate.setDefaultLang('en');
            translate.use(langToSet).subscribe(() => {
                console.info(`Successfully initialized '${langToSet}' language.'`);
            }, err => {
                console.error(`Problem with '${langToSet}' language initialization.'`);
            }, () => {
                resolve(null);
            });
        });
    });
}

@NgModule({
    declarations: [
        AppComponent,
        PageNotFoundComponent,
        HomePageComponent,
        MsgPipe
    ],
    imports: [
        BrowserModule,
        RouterModule.forRoot(appRoutes),
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        }),
    ],
    providers: [
        {
            provide: APP_INITIALIZER,
            useFactory: appInitializerFactory,
            deps: [TranslateService, Injector],
            multi: true
        }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

(上面的代码摘自here)

除非pure设置为false,否则我的管道仍然无法工作,这会导致多次不必要的调用。没有错误,只是不会改变内容。

EN

回答 5

Stack Overflow用户

发布于 2018-07-18 21:19:14

如果你做了管子不纯的工作...但我认为这不是解决这个问题的最好方法。

代码语言:javascript
复制
@Pipe({
  name: 'msg',
  pure: false
})
export class TranslationPipe extends TranslatePipe {
票数 2
EN

Stack Overflow用户

发布于 2017-09-27 00:53:17

您不需要任何额外的库来进行翻译。例如,您只需要一个管道文件、translation-pipe.ts文件和translation.provder.ts文件,并且您可以扩展任何您想要的内容。请检查以下文件

translation-pipe.ts

代码语言:javascript
复制
import { Pipe, PipeTransform } from '@angular/core';

import {TranslateProvider} from '../../providers/translate/translate';

@Pipe({
  name: 'translation',
})
export class TranslationPipe implements PipeTransform {

  constructor(private _translateService: TranslateProvider) { }

  transform(value: string, ...args) {
    return this._translateService.instant(value);
  }
}

TranslateProvider.ts

代码语言:javascript
复制
import {Injectable} from '@angular/core';
import {LANG_EN_TRANS} from './languages/en';
import {LANG_TR_TRANS} from './languages/tr';

@Injectable()
export class TranslateProvider {

  private _currentLang: string;
  // If you want to use dictionary from local resources
  private _dictionary = {
    'en': LANG_EN_TRANS,
    'tr': LANG_TR_TRANS
  };

  // inject our translations
  constructor( private _db: DbProvider) { }

  public get currentLang() {
     if ( this._currentLang !== null) {
       return this._currentLang;
     } else return 'en';
  }

  public use(lang: string): void {
    this._currentLang = lang;
  } // set current language

  // private perform translation
  private translate(key: string): string {

   // if u use local files
    if (this._dictionary[this.currentLang] && this._dictionary[this.currentLang][key]) {
      return this._dictionary[this.currentLang][key];
    } else {
      return key;
    }

   // if u do not want local files then get a json file from database and add to dictionary
  }

  public instant(key: string) { return this.translate(key); }
}

这里,private translate()函数是将本地键更改为language的主函数。您可以导入本地文件,如en.ts、sp.ts、au.ts等,也可以修改此函数以连接数据库并获得键值对……本地转换文件的示例如下

en.ts

代码语言:javascript
复制
export const LANG_EN_TRANS = {
  'about': 'About',
}

tr.ts

代码语言:javascript
复制
export const LANG_TR_TRANS = {
  'about': 'Hakkinda',
}

有一个很好的编码...

票数 1
EN

Stack Overflow用户

发布于 2020-11-20 21:59:17

translatepipe本身是不纯的(参见:https://github.com/ngx-translate/core/blob/master/projects/ngx-translate/core/src/lib/translate.pipe.ts),因为它需要对可观察到的翻译的变化做出反应。

您还应该只调用super.transform(key,...args)而不是instant(...)。这种方法在我们的项目中有效。或者请说明为什么需要使用instant。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46431752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档