【问题标题】:Angular 2 custom pipe with Dependency Injection带有依赖注入的Angular 2自定义管道
【发布时间】:2017-10-25 10:39:51
【问题描述】:

假设我像这样创建了一个管道:

import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({
  name: 'awesomePipe'
})
export class AwesomePipe implements PipeTransform {
  constructor(private currency: CurrencyPipe){}

  transform(value: number) {
    return this.currency
      .transform(value.toString(), 'USD', true)
      .substring(0, 3) + 'bajillion dollars';
  }
}

然后将其注入组件中:

import { AwesomePipe } from '../pipes/awesome.pipe';
 ......
 ......
export class Awesome {
  awesomeness:[number] = [123123123123,32131231235,56465434565];

  constructor(private awesome: AwesomePipe){}
}

并用于:

template: `
<div class="foo">
  <custom-component
    [displayValues]="awesomeness.map(awesome.transform)"
  ></custom-component>
</div>
`,

在转换函数中失败:

VM8019:1 Uncaught ReferenceError: currency is not defined

在转换函数中添加调试器将this 显示为未定义。

为什么?我该如何解决这个问题?

【问题讨论】:

    标签: angular dependency-injection angular2-components angular2-pipe angular2-injection


    【解决方案1】:

    我想你可以像这样将 awesome-context 绑定到你的 awesome.transform 方法来解决这个问题:

    template: `
    <div class="foo">
      <custom-component
        [displayValues]="awesomeness.map(awesome.transform.bind(awesome))"
      ></custom-component>
    </div>
    `,
    

    但实际上,当您真正想要显示转换后的值时,最好只在您的自定义组件中传递令人敬畏的值并使用您的管道。这样你就可以使用这里描述的管道链接:https://angular.io/docs/ts/latest/guide/pipes.html#chaining-pipes

    【讨论】:

      猜你喜欢
      • 2016-10-02
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多