angular2-services - 如何在 Angular 2 中的自定义管道中使用服务

标签 angular2-services angular2-pipe

我想在 html 上显示年份中的月份。我的过滤器需要几个月的时间作为输入,它应该返回几年。

例如:如果输入 12,则应返回翻译后的值 1 年。如果超过 1 年,则应返回“2 年”。

我的管道包含:

import { Pipe, PipeTransform} from '@angular/core';

@Pipe({name : 'displayMonthsInYears '})
export class DisplayMonthsInYears implements PipeTransform{
    transform(noOfMonths : number) : any {
         if(noOfMonths > 12){
            return (noOfMonths / 12 + $translate.instace('YEARS'));
         }
         return (noOfMonths / 12 + $translate.instace('YEAR'));
    }
}

html 是:

 <div class="text-left">
     {{ contractDuration | displayMonthsInYears }}
 </div>

我不知道如何实现这一点。请帮忙。

最佳答案

使用以下命令安装翻译库及其 http-loader

npm install @ngx-translate/core @ngx-translate/http-loader --save

遵循@ngx-translate文档中的设置指南。然后导入服务:

import {TranslateService} from '@ngx-translate/core';

将其注入(inject)管道并像这样使用它:

@Pipe({name : 'displayMonthsInYears '})

export class DisplayMonthsInYears implements PipeTransform{

  constructor(private translate: TranslateService) {}

  transform(noOfMonths : number) : any {

     if (noOfMonths > 12) {
        return (noOfMonths / 12 + this.translate.instant('YEARS'));
     }

     return (noOfMonths / 12 + this.translate.instant('YEAR'));
  }
}

instant 将立即返回值,还有一些有用的值,例如 stream,它将为您提供一个可观察对象,即使在语言变化。 get 不会。您可以使用更多方法,因此我建议您查看文档并了解最适合您的方法。

关于angular2-services - 如何在 Angular 2 中的自定义管道中使用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44902113/

相关文章:

angular2 [ngClass] 上的管道表达式不起作用

javascript - Angular2 在 Component.js 中使用管道

Angular 2 : Error while using a text filter pipe to filter an array

javascript - Angular4 *ng如果不工作/变量未定义

angular - 惰性加载模块可以共享其父级提供的相同服务实例吗?

angular - 使用 i18n 选择管道

Angular2 + 异步管道 : Get multiple values from a single Observale

angular - Observable.subscribe() 只工作一次 (ngrx\angular2)

javascript - Angular 2 Exception : TypeError: 'caller' , 'callee' 和 'arguments' 属性可能在严格模式函数或参数对象上

Angular2 Bootstrap Providers 与在组件中提供数组