RxJs extension methods

Andrei Mihalciuc
1 min readOct 20, 2017

As my background is C#, there was something missing in TypeScript (or at least I didn’t know how to do) - extension methods.

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Let’s image you have an Angular application with many calls to api using HttpClient which uses RxJs and returns Observable. Most of the calls will have the same structure: you handle success and error responses in subscribe method:

this.httpClient.get<any>(‘path/to/api’)
.subscribe(
response => ... handle success,
err => // handle error
)

Wouldn’t it be great if we could change it to:

this.httpClient.get<any>(‘path/to/api’)
.subscribeWithErrorHandling(response => ... handle success)

Typescript handbook (Module augmentation section) describes how Observable’s map operator is created. We are going to use the same approach to implement our subscribeWithErrorHandling operator:

// obserable.extensions.tsdeclare module 'rxjs/Observable' {
interface Observable<T> {
subscribeWithErrorHandling(
this: Observable<T>,
nextFunc: (response: T) => void
): void ;
}
}
Observable.prototype.subscribeWithErrorHandling =
function(
this: Observable<any>,
nextFunc: (response: any) => void
): void {
this.subscribe(action => nextFunc(action),
(error) => {
// your error handling
console.log(error);
});
};

To use it:

// component.ts
import './observable.extensions'
this.httpClient.get<any>(‘path/to/api’)
.subscribeWithErrorHandling(response => ... handle only success)

Summary

As you can see it is really straightforward and using the same approach you can to add your own “extension methods” to Observable. Happy coding!

--

--