Skip to content

Instantly share code, notes, and snippets.

@MarsiBarsi
Last active November 30, 2020 03:44
Show Gist options
  • Save MarsiBarsi/8b08a7bbf80328aa3d60ceb3ac6b1814 to your computer and use it in GitHub Desktop.
Save MarsiBarsi/8b08a7bbf80328aa3d60ceb3ac6b1814 to your computer and use it in GitHub Desktop.
static-request.service.ts
@Injectable({ providedIn: 'root' })
export class StaticRequestService {
private readonly cache = new Map<string, Observable<string>>();
request(url: string): Observable<string> {
const cache = this.cache.get(url);
if (cache) {
return cache;
}
// use new Observable() to create
const observable = new Observable((observer: Observer<string>) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
const response = xhr.responseType ? xhr.response : xhr.responseText;
if (xhr.status === 200) {
observer.next(response);
observer.complete();
} else {
observer.error(response);
}
}
};
xhr.open('GET', url, true);
xhr.send();
return () => {
xhr.abort();
};
});
const piped = observable.pipe(shareReplay(1));
this.cache.set(url, piped);
return piped;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment