angulardependency-injectionangular2-componentsangular2-pipeangular2-injection

Angular 2 custom pipe with Dependency Injection


Say I create a pipe like so:

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';
  }
}

This is then injected in a component with:

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

  constructor(private awesome: AwesomePipe){}
}

And used with:

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

Which fails in the transform function with:

VM8019:1 Uncaught ReferenceError: currency is not defined

Adding a debugger in the transform function show this as being undefined.

Why? And how can I fix this?


Solution

  • I guess you can fix this when you bind the awesome-context to your awesome.transform method like so:

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

    but actually it would be better to just pass the awesomeness values in your custom-component and using your pipes when you actually want to display the transformed values. this way you could use the pipe chaining as descibed here: https://angular.io/docs/ts/latest/guide/pipes.html#chaining-pipes