Skip to content

Instantly share code, notes, and snippets.

@tdbrian
Created October 4, 2018 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdbrian/756222bdacb6cae0cd110e94a56ede2c to your computer and use it in GitHub Desktop.
Save tdbrian/756222bdacb6cae0cd110e94a56ede2c to your computer and use it in GitHub Desktop.
Angular data handler for async data calls.
import { BehaviorSubject, Observable } from 'rxjs';
export class DataHandler<T> {
value: T;
value$: BehaviorSubject<T>;
isLoading = false;
hasError = false;
error: any = null;
errorIsString = false;
successful = false;
private defaultValue: T;
constructor(defaultValue: T = null) {
if (defaultValue) {
this.defaultValue = defaultValue;
this.value = defaultValue;
this.successful = true;
}
this.value$ = new BehaviorSubject<T>(defaultValue);
}
async request(response: Observable<T>): Promise<T> {
this.isLoading = true;
this.hasError = false;
this.error = null;
this.successful = false;
this.errorIsString = false;
try {
const result = await response.toPromise();
this.value$.next(result);
this.value = result;
this.successful = true;
return result;
} catch (err) {
if (typeof err.error === 'string') {
try {
this.error = JSON.parse(err.error);
} catch (error) {
this.error = err.error;
this.errorIsString = true;
}
} else {
this.error = err.error;
}
this.hasError = true;
} finally {
this.isLoading = false;
}
}
setErrorState(error: string) {
this.reset();
this.hasError = true;
this.error = error;
this.errorIsString = true;
}
reset() {
this.value = null;
this.isLoading = false;
this.hasError = false;
this.error = null;
this.value$ = new BehaviorSubject<T>(this.defaultValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment