Often, one wants to use different sets of values depending on user's choice. For example different ways of saying the same thing depending on the selected language, or different color of the same type depending on the selected theme. I'm curently trying to do the latter, so I made several JSON files with the same keys but different values. This is the 'green_theme' JSON:
{
"darker_color": "#1a3300",
"lighter_color": "#4f9900",
"error_color": "#b42805"
}
and now I want components to take the color codes that they need from an injected service like so:
<div [style.color]="themeService.getColorCodeByKey('darker_color')">example</div>
This is how I tried implementing the service:
@Injectable()
export class ThemeService {
private readonly RED_SKIN_SOURCE = "assets/themes/red_skin.json"
private readonly GREEN_SKIN_SOURCE = "assets/themes/green_skin.json"
private readonly YELLOW_SKIN_SOURCE = "assets/themes/green_skin.json"
public skinData: {[key: string]: string} = {};
constructor(private http:Http) {
this.setSkin(ThemeService.Skin.Green);
}
getColorCodeByKey(key: string): string {
return this.skinData[key];
}
public setSkin(skin: ThemeService.Skin) {
let observable: Observable<Response>;
switch(skin) {
case ThemeService.Skin.Red: {
observable = this.http.get(this.RED_SKIN_SOURCE);
break;
}
case ThemeService.Skin.Yellow: {
observable = this.http.get(this.YELLOW_SKIN_SOURCE);
break;
}
case ThemeService.Skin.Green: {
observable = this.http.get(this.GREEN_SKIN_SOURCE);
break;
}
}
observable.map((res: Response) => res.json().forEach(element => {
this.skinData[element.key] = element;
}));
}
}
export namespace ThemeService {
export enum Skin {
Red,
Green,
Yellow
}
}
But it seems like the setSkin method leaves skinData empty? How to do this correctly? Am I mapping the Observable too soon? Or is this just not how .json() works?
ALTERNATIVELY If you had a better idea how to implement this key-value-like service, I'm not against giving up on JSON.. I was even thinking of implementing it my own way with my own format and parser
resandres.json()into console to see what it gets? It looks like theres.json().forEachmight not work cause it doesn't return an enumerable object.