UNPKG

ngx-http-request-state

Version:

Angular library for wrapping HttpClient responses with loading & error information to allow observing load/loading/error state changes as a stream of events.

101 lines (94 loc) 3.12 kB
import { HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { map, startWith, catchError } from 'rxjs/operators'; function loadingState(value) { return { isLoading: true, value, error: undefined, }; } /** * Returns a new LoadedState instance, with the optional value as the loaded data. * * @param value */ function loadedState(value) { return { isLoading: false, error: undefined, value, }; } function errorState(error, value) { return { isLoading: false, error, value, }; } function isLoadingState(state) { return !!state && state.isLoading; } function isLoadedState(state) { return !!state && !state.isLoading && !state.error; } function isErrorState(state) { return !!state && !state.isLoading && !!state.error; } function httpRequestStates(mapResponse) { return (source) => source.pipe(map((result) => loadedState(mapResponse ? mapResponse(result) : result instanceof HttpResponse ? result.body : result)), startWith(loadingState()), catchError((err) => of(errorState(err)))); } /** * Given an array of HttpRequestState<T>, merge them together into a new single HttpRequestState<T>, * based on a supplied merging strategy of values (mergeValues) or of errors (mergeErrors). * * One can think of this function as allowing one to act "inside" the states, directly on the values or errors. * * Use this with combineLatest, instead of forkJoin, to get loading updates. * * @param states Array of states of the same type that should be merged together. * @param mergeValues Handles how to merge values together when all states have loaded. * @param mergeErrors Handles how to merge errors together in case one or more of the states end up in ErrorState. * If not specified, the first error is simply used as the error of the merged state * @returns The merged HttpRequestState<T> */ function mergeStates(states, mergeValues, mergeErrors) { if (states.every(isLoadedState)) { const state = { isLoading: false, value: mergeValues(states.map((s) => s.value)), error: undefined, }; return state; } if (states.some(isErrorState)) { if (mergeErrors === undefined) { mergeErrors = (errors) => errors[0]; } const errorStates = states.filter(isErrorState); const state = { isLoading: false, value: undefined, error: mergeErrors(errorStates.map((s) => s.error)), }; return state; } // If one of the state is still not loaded and there are no errors // the merged state is still considered loading. const state = { isLoading: true, value: undefined, error: undefined, }; return state; } /** * Generated bundle index. Do not edit. */ export { errorState, httpRequestStates, isErrorState, isLoadedState, isLoadingState, loadedState, loadingState, mergeStates }; //# sourceMappingURL=ngx-http-request-state.mjs.map