Last active
October 5, 2020 14:55
-
-
Save alexanderbartels/f426a98ca2a6f97dbd14d3f9b9c29e1c to your computer and use it in GitHub Desktop.
Angular Recipe for a configuration service that caches the result and works with rxjs
This file contains hidden or 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
{ | |
"toggles": { | |
"foo": "bar" | |
}, | |
"availableLanguages": ["de", "en", "jp"] | |
} |
This file contains hidden or 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 { Injectable } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
@Injectable() | |
export class ConfigService { | |
private config$: Observable<ObservedValueOf<Promise<object>>>; | |
constructor(private http: HttpClient) { | |
// use a promise to load the configuration once the service is created | |
const configPromise = new Promise((resolve) => { | |
// load config only once and direct after instance is created | |
this.http.get("/config.json").subscribe((config) => { | |
resolve(config); | |
}); | |
}); | |
// create stream out of the config promise, so it will be only loaded once | |
// @ts-ignore | |
this.config$ = defer(() => configPromise); | |
} | |
/** | |
* Get toggles from config | |
*/ | |
getToggles(): Observable<any> { | |
return this.config$ | |
.pipe(pluck('toggles')); | |
} | |
/** | |
* Get available languages from config | |
*/ | |
getAvailableLanguages(): Observable<any> { | |
return this.config$ | |
.pipe(pluck('availableLanguages')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment