Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何延伸ngx平移管道_Angular_Angular Pipe_Ngx Translate - Fatal编程技术网

Angular 如何延伸ngx平移管道

Angular 如何延伸ngx平移管道,angular,angular-pipe,ngx-translate,Angular,Angular Pipe,Ngx Translate,我想扩展ngx translate的管道,使其在我的应用程序中具有潜在的多用途 我的烟斗: import { Pipe, PipeTransform } from '@angular/core'; import { TranslatePipe } from "@ngx-translate/core"; @Pipe({ name: 'msg' }) export class MsgPipe extends TranslatePipe implements PipeTransform {

我想扩展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)
  }
}
为了等待相关的翻译模块加载,我使用了Angular的APP_初始值设定项:

app.module:

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 { }
从'@angular/platform browser'导入{BrowserModule};
从“@angular/core”导入{NgModule};
从'@angular/router'导入{RouterModule};
从'@angular/common/http'导入{HttpClientModule,HttpClient};
从'@ngx translate/http loader'导入{TranslateHttpLoader};
从“/app.routes”导入{appRoutes};
从“./root/app.component”导入{AppComponent};
从“./shared/components/page not found/page not found.component”导入{PageNotFoundComponent};
从“./shared/components/HomePage/HomePage.component”导入{HomePageComponent};
从“./shared/pipes/msg.pipe”导入{MsgPipe};
从'@angular/core'导入{ChangeDetectorRef};
从“@ngx translate/core”导入{TranslateModule,TranslateLoader}”;
从“@angular/core”导入{Injector,APP_INITIALIZER};
从'@ngx translate/core'导入{TranslateService};
从“@angular/common”导入{LOCATION_INITIALIZED}”;
导出函数HttpLoaderFactory(http:HttpClient){
返回新的TranslateHttpLoader(http);
}
导出函数appInitializerFactory(翻译:翻译服务,注入器:注入器){
return()=>新承诺)


除非pure设置为false,否则My pipe仍然无法工作,这会导致多个不必要的调用。没有错误,它只是不会更改内容。

您不需要任何额外的翻译库。例如,您只需要一个管道文件
translation pipe.ts
文件和
translation.provider.ts
文件,您可以扩展任何需要的文件您需要。请检查以下文件

翻译管道.ts

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);
  }
}
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); }
}
export const LANG_EN_TRANS = {
  'about': 'About',
}
export const LANG_TR_TRANS = {
  'about': 'Hakkinda',
}
TranslateProvider.ts

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);
  }
}
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); }
}
export const LANG_EN_TRANS = {
  'about': 'About',
}
export const LANG_TR_TRANS = {
  'about': 'Hakkinda',
}
这里的
private translate()
函数是将本地密钥更改为语言的主要函数。您可以导入本地文件,如en.ts、sp.ts、au.ts等,也可以修改此函数以连接数据库并获取密钥-值对。。。 本地翻译文件的示例是

en.ts

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);
  }
}
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); }
}
export const LANG_EN_TRANS = {
  'about': 'About',
}
export const LANG_TR_TRANS = {
  'about': 'Hakkinda',
}

tr.ts

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);
  }
}
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); }
}
export const LANG_EN_TRANS = {
  'about': 'About',
}
export const LANG_TR_TRANS = {
  'about': 'Hakkinda',
}

有一个很好的编码…

如果你做管道不纯工程…但我认为这不是最好的解决办法

@Pipe({
  name: 'msg',
  pure: false
})
export class TranslationPipe extends TranslatePipe {

translatepipe本身是不纯的(参见:),因为它需要对可观察到的翻译的变化做出反应


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

接受字符串枚举数组并将其转换为转换字符串数组的管道示例

import { ChangeDetectorRef, Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { AlertEnum } from '../alert.enum';

@Pipe({
  name: 'translateAlertArray',
  pure: false
})
export class TranslateErrorsArrayPipe
  extends TranslatePipe
  implements PipeTransform {
  constructor(
    private translateService: TranslateService,
    private changeDetectionRef: ChangeDetectorRef
  ) {
    super(translateService, changeDetectionRef);
  }

  transform(alerts: any): string[] {
    return alerts?.map((alert: AlertEnum) =>
      super.transform('alerts.' + AlertEnum[alert])
    );
  }
}

我知道你在做什么,我只是想知道你为什么不使用ngx之类的东西,你自己写这篇文章有什么特别的原因吗?因为ngx是一个第三方库,你说我想定制,因为你不需要ngx,你只需要一个管道文件和提供程序,它可以做同样的事情…:)你如何以安全的方式处理插值库提供了传入对象和替换字符串变量的选项,您的解决方案解决了这个问题吗?您解决了吗?我也有同样的问题…恐怕我记不起来了,我想我选择了一种完全不同的方法