Using Custom Pipes in services in angular2

976 Views Asked by At

I want to call the my custom pipe inside Injectable service. I checked many threads in stackoverflow. But they talk about using custom pipes inside a component. Can u please help me here, any helpful link will be fine. Below is my custom pipe file:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'unit' })
export class UnitPipe implements PipeTransform {
    transform(val,unit, args) {
        if(unit=='Metric') {
            return val * 2;
        }
        else {
            return val * 4;
        }
    }
}

And Iam trying to access this pipe in my service:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { UnitPipe } from '../pipes/UnitPipe';
@Injectable()
export class SomeService {
    constructor(http: Http, unitPipe: UnitPipe) {
        this.http = http;
        this.unitPipe = unitPipe;
    }
    transformUnit() {
        return this.unitPipe.transform('10', 'Metric');
    }
}

I have specified this in app.module.js

declarations: [UnitPipe],
providers: [UnitPipe]

And in my component.js, I am calling this service method & just checking the output in console:

import { Component, OnInit, EventEmitter, Input } from '@angular/core';
import { SomeService } from '../../services/SomeService';
@Component({
})
export class SomeClass implements OnInit {
    constructor(someService: SomeService) {
        this.someService = someService;
    }
    ngOnInit(): void {          
        console.log(this.someService.transformUnit());            
    }
}

But Iam getting below error

enter image description here

One more thing is, my plan is to call transformUnit method inside my service file 'SomeService', may be onload, where the function definition is present. Any thought on this?

Thank you.

1

There are 1 best solutions below

0
benshabatnoam On

Your pipe transform function expects 3 parameters:

transform(val,unit, args) {
  ...
}

You're providing only 2 parameters to it:

transformUnit() {
    return this.unitPipe.transform('10', 'Metric');
}

Best solutions I can suggest is using an Optional/Default parameter:

Optional parameter - Change args to args?

OR

Default parameter - Change args to args = null // or some other default value

This will allow you to call the pipe function with 2 params, so no need for code changing in your service.

You can see in this TypeScirpt-Functions link, section called Optional and Default Parameters for more details.

Created a simple StackBlitz DEMO with your code to this in action. Initially you will see the error in SomeService file. Just change the pipe args param accordingly. refresh the page. The error is gone in SomeService.