Pipe Function
pipe() Function
The pipe() function provides the ability to combine existing operators together to create a new operator.
Example
Let's use the pipe() function to create a new logger() operator.
The logger() operator will accept an optional loggerType operator that will specify the type of log message to output to the console.
import { pipe } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, tap } from 'rxjs/operators';
interface UserResponse {
page: number;
per_page: number;
total: number;
total_pages: number;
data: {
id: number;
email: string;
first_name: string;
last_name: string;
avatar: string;
}[];
}
enum LoggerType {
Count,
Debug,
Dir,
Log,
Table
}
const getLoggerByType = (loggerType: LoggerType): ((value: any) => void) => {
switch (loggerType) {
case LoggerType.Count:
return console.count;
case LoggerType.Debug:
return console.debug;
case LoggerType.Dir:
return console.dir;
case LoggerType.Log:
return console.log;
case LoggerType.Table:
return console.table;
}
};
const logger = (loggerType = LoggerType.Log) =>
pipe(tap(getLoggerByType(loggerType)));
ajax
.getJSON<UserResponse>('https://reqres.in/api/users')
.pipe(
map((response) => response.data),
logger(),
logger(LoggerType.Table)
)
.subscribe();
In the example above we've defined a new LoggerType enumerator for each of the type of logging outputs supported by our logger() operator.
We'll use the console object's methods for each type accordingly.
The getLoggerByType() is a helper function to return a reference the console object method.
The operator itself is fairly short:
- We create a new function that accepts the optional
loggerTypeargument and default to theLoggerType.Logvalue. - Using the
pipe()function we pass the emitted next notification value to thetap()operator, which will invoke the appropriate console method. - In our implementation we are fetching users from the API, using the
map()operator to access thedataproperty that contains the array of user object. First we use thelogger()operator without any arguments, which should use theconsole.log()method. Then, we use thelogger()operator and specify theLoggerType.Tablefor theloggerTypeargument.