Created
October 4, 2018 13:31
-
-
Save tdbrian/756222bdacb6cae0cd110e94a56ede2c to your computer and use it in GitHub Desktop.
Angular data handler for async data calls.
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 { 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