代码之家  ›  专栏  ›  技术社区  ›  Aqeel Ashiq

角度转换服务,在嵌套的json中插入参数

  •  11
  • Aqeel Ashiq  · 技术社区  · 7 年前

      "SampleField": {
        "SampleValidation": {
          "MIN": "Value should not be less than {{min}}", 
          "MAX": "Value should not be more than {{max}}", 
        }
      }
    

    我的角度代码:

    ngOnInit(): void {
      this.translateService.get('SampleField.Validation', {
        // using hard coded value just as a sample
        min: 0, max: 2000
      }).subscribe(translation => {
        console.log(translation);
      });
    }
    

    预期输出:

    {
        MIN: "Value should not be less than 0",
        MAX: "Value should not be greater than 2000"
    }
    

    {
        MIN: "Value should not be less than {{min}}",
        MAX: "Value should not be greater than {{max}}"
    }
    
    2 回复  |  直到 4 年前
        1
  •  11
  •   Sibeesh Venu    4 年前

    根据 source of ngx-translate 插值仅适用于字符串:

    export abstract class TranslateParser {
    /**
     * Interpolates a string to replace parameters
     * "This is a {{ key }}" ==> "This is a value", with params = { key: "value" }
     * @param expr
     * @param params
     * @returns {string}
     */
    abstract interpolate(expr: string | Function, params?: any): string;
    

    this.translateService.get([
        'SampleField.Validation.MIN', 
        'SampleField.Validation.MAX'
      ], {
      // using hard coded value just as a sample
      min: 0, max: 2000
    }).subscribe(translation => {
      console.log(translation);
    });
    
        2
  •  1
  •   Sibeesh Venu    4 年前

    您也可以使用 translate 管道,以便您可以删除对组件的附加服务依赖关系。

    <p *ngIf="!item?.isRemovable">
    {{'i18n.dashboard.heading' 
    | translate:{'TEXTTOFIND': 'STRINGTOREPLACE'} }}
    </p>
    

    i18n.test.key 有这个 TEXTTOFIND 插值。类似下面的内容。

    "heading": "This is with the interpolated {{TEXTTOFIND}} text."
    

    {{}} 在标题字符串和 STRINGTOREPLACE