Last active
November 30, 2020 03:44
-
-
Save MarsiBarsi/8b08a7bbf80328aa3d60ceb3ac6b1814 to your computer and use it in GitHub Desktop.
static-request.service.ts
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
@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