试图继承扩展ngx-translate管道功能,但返回空字符串。

问题描述 投票:0回答:1

正是标题中所说的。我试图从 translatePipe 继承,但它的结果是一个空字符串。当我使用常规的translatePipe时,一切都很好,但当我把它改为我的自定义动态TranslatePipe时,它是一个空字符串,而不是我的翻译。

//shared.module.ts
import { CommonModule } from '@angular/common';
import { NgModule, ChangeDetectorRef } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateModule, TranslateLoader, TranslateService, LangChangeEvent, TranslatePipe } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";

import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';


// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient,'./assets/i18n/', '.json');
}  



@Pipe({name:'dynamicTranslate'})
export class dynamicTranslatePipe extends TranslatePipe implements PipeTransform{
  constructor( translate: TranslateService,  _ref: ChangeDetectorRef){
    super(translate, _ref)
  }

  transform(baseText: string): string { 

    let result = super.transform(baseText)
    return result
  }
}

@NgModule({
 imports: [ 
    CommonModule,
    TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
        }
      }),
    FontAwesomeModule,

    ],
 declarations: [ dynamicTranslatePipe ],
 exports:      [ CommonModule, FormsModule, TranslateModule, FontAwesomeModule, dynamicTranslatePipe ]
})
export class SharedModule { }
angular typescript internationalization ngx-translate angular-i18n
1个回答
1
投票

你必须通过设置pure: false来使用不纯管道。

@Pipe({
  name: 'dynamicTranslate',
  pure: false
})

但这样你的管道就会在每次变化检测时运行。你可能想使用 changeDetection: ChangeDetectionStrategy.OnPush 在您的compnent decorator中。使用OnPush,只有当输入属性改变或事件被触发时,才会检查组件的绑定。

© www.soinside.com 2019 - 2024. All rights reserved.