Skip to content

Instantly share code, notes, and snippets.

@alexanderbartels
Last active October 5, 2020 14:55
Show Gist options
  • Save alexanderbartels/f426a98ca2a6f97dbd14d3f9b9c29e1c to your computer and use it in GitHub Desktop.
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
{
"toggles": {
"foo": "bar"
},
"availableLanguages": ["de", "en", "jp"]
}
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