Angular Pipes: Custom Pipe — An API Call

Ghanshyam Shukla
2 min readSep 27, 2019

Introduction

Angular pipes, a way to write display-value transformations that you can declare in your HTML. A pipe takes in data as input and transforms it to a desired output. Angular comes with a stock of in-built pipes such as date | uppercase | lowercase | currency | percent etc.

<h1>Today is {{ todayDate | date }} </h1>

Custom Pipe Syntax & Explanation

Angular provides a way where you can create your own pipe. It is a kind of plug & play which is very efficient, easy to ease, less effort to create & maintain, and of course shareable across application.

import { Pipe, PipeTransform } from '@angular/core';@Pipe({name: 'pipename'})export class CustomPipe implements PipeTransform { 
transform(value: any): any {
// write logic and return formatted value
}
}
}

Custom pipes can be use in the same way as built-in pipes.

Include custom pipe in the AppModule

You can also provide it in the providers array of your NgModule.

API call in custom pipes

You can also call API using custom pipes. While doing so, make sure to set the variable pure = false while declaring pipe for e.g.

mport { HttpClient } from '@angular/common/http';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'apiCallPipe',
pure: false
})

An impure pipe executes during every component change detection cycle called on keystroke or mouse-move

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

@Pipe({
name: 'apiCallPipe',
pure: false
})

export class ApiCallPipe implements PipeTransform {

private data: any = null;

constructor(private http: HttpClient) { }

transform(url: string): any {

this.http.get(url).subscribe(result => {
// You could also cache your result this.data = result;

return this.data;
});
}
}
}

Impure pipes are executed after every few milliseconds. Please be careful, otherwise API will experience so many requests. Implement some type of data caching or other logic to save the response and call the API only when required.

Demonstration

Import the pipe on the component and call the same on the template with | symbol

<div *ngFor=”let employee of (‘apiUri’ | apiCallPipe)“> {{employee.name}} </div>

This way we can implement API call in custom pipes.

Happy coding !!!

#angular #pipes #typescript

--

--