@aviellv/async-request-rxjs-pipe

1.0.1 • Public • Published

async-request

npm version Build Status

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>

/@aviellv/async-request-rxjs-pipe/

    Package Sidebar

    Install

    npm i @aviellv/async-request-rxjs-pipe

    Weekly Downloads

    1

    Version

    1.0.1

    License

    Apache-2.0

    Unpacked Size

    5.08 kB

    Total Files

    6

    Last publish

    Collaborators

    • aviellv