With loading pipe long living stream #tags: Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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