简体   繁体   中英

Using Custom Pipes in services in angular2

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

在此处输入图片说明

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM