@aviellv/async-request-rxjs-pipe
v1.0.1
Published
A pipe functions for rxjs 6+ which emits a three-state 'async-request' with a typed loading/sucess/error status object
Downloads
6
Maintainers
Readme
async-request
A pipe function for rxjs 6+ which emits a three-state 'async-request' with a typed loading/success/error status object
Motivation
A common use case for consuming streams is displaying a loading animation, the data itself on success or a failure message when it errors. This pipe is meant to reduce boiler-plate to a minimum and expose these three states in an easy to consume way.
Example usage
this.httpQuery$ = this.http.get<string>("./api/text").pipe(asAsyncRequest<string, HttpErrorResponse>());
this.httpQuery$.subscribe(response => {
switch (response.state) {
case "loading":
showLoadingAnimation();
break;
case "success":
showData(response.value);
break;
case "error":
showError(response.value.message);
break;
}
});
it gets even better when binding in views like in angular with the async pipe:
<span *ngIf="(httpQuery$ | async) as response">
<ng-container [ngSwitch]="response.state">
<ng-container *ngSwitchCase="'loading'">loading data...</ng-container>
<ng-container *ngSwitchCase="'success'">{{response.value}}</ng-container>
<ng-container *ngSwitchCase="'error'">{{response.value}}</ng-container>
</ng-container>
</span>