如何在带有 Angular 的打字稿中使用翻译管道

问题描述

我想在单击按钮时显示已翻译的消息,因此我需要在打字稿中使用翻译管道。

这是我的json:

 "newRepair": {
   "intake": {
       "errormessage" : "This is a required field"
      }
     }

这是TS中按钮相关的功能

 error : string;
 saveAndGoForUpload(){
   this.error = this.translatePipe.transform("newRepair.intake.errormessage");}

HTML:

<button  (click)="saveAndGoForUpload()" type="button"
     class="btn">PROCEED</button>
 <p>{{error}}</p>

它给了我这个错误NullInjectorError: No provider for TranslatePipe!

解决方法

如果你想在组件中使用管道的transform()方法,你还需要将CustomPipe添加到模块的提供者中:

import  { CustomPipe } from '../pipes/custom.pipe';

@NgModule({
  imports:      [ ... ],declarations: [ AppComponent,CustomPipe ],providers: [CustomPipe],bootstrap:    [ AppComponent ]
})
export class AppModule { }

,

您需要在类组件装饰器中添加自定义管道作为提供者:

import  { CustomPipe } from '../pipes/custom.pipe';

@Component({
    templateUrl: './some.component.html',providers: [CustomPipe]
})
export class SomeComponent{
}

或者在模块级别,取决于您计划在何处使用管道。