Skip to content

Instantly share code, notes, and snippets.

@VaLeXaR
Forked from alexzuza/with-loading.pipe.ts
Last active February 19, 2020 18:31
Show Gist options
  • Save VaLeXaR/a76f0fa6e12c95a162ca483a134308e4 to your computer and use it in GitHub Desktop.
Save VaLeXaR/a76f0fa6e12c95a162ca483a134308e4 to your computer and use it in GitHub Desktop.
With loading pipe long living stream #tags: Angular
<h2 class="title">Products</h2>
<div class="search-bar">
<input (input)="searchStream$.next($event.target.value)">
</div>
<div class="results">
<h3>Built-in solution</h3>
<div *ngIf="obs$ | async as obs">
<ng-template [ngIf]="obs.type === 'finish'">
{{obs.value}}
</ng-template>
<ng-template [ngIf]="obs.type === 'start'">Loading...</ng-template>
</div>
<h3>WithLoadingPipe</h3>
<div *ngIf="obs$ | withLoading | async as obs">
<ng-template [ngIf]="obs.value">{{ obs.value }}
</ng-template>
<ng-template [ngIf]="obs.loading">Loading...</ng-template>
</div>
</div>
import { Pipe, PipeTransform } from '@angular/core';
import { isObservable, of } from 'rxjs';
import { map, startWith, catchError } from 'rxjs/operators';
@Pipe({
name: 'withLoading',
})
export class WithLoadingPipe implements PipeTransform {
transform(val) {
return isObservable(val)
? val.pipe(
map((value: any) => ({
loading: value.type === 'start',
value: value.type ? value.value : value
})),
startWith({ loading: true }),
catchError(error => of({ loading: false, error }))
)
: val;
}
}
/*obs$ = this.searchStream$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap((query) =>
concat(
// emit { type: 'start' } immediately
of({ type: 'start'}),
this.productsService.getByFilter(query)
// map to the wrapped object with type finish
.pipe(map(value => ({ type: 'finish', value })))
})
);*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment