I made a service that gets some userdata from a remote source. The service a method for getting multiple users, and one for getting a specific user. The observables returned from the two methonds get .pipe(ed) thru a map() to be able to mutate the user-objects before they get consumed.
What I want is to only define the mutators once, for both the multiple users stream and the single users stream, but I run into scope problems with my current approach.
Be aware that I call users "heroes". This is a design aspect. Following are the corresponding methods from my HeroService class:
export class HeroService {
// [...]
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl).pipe(
map((heroes: Hero[]) => this.mutateHeroes(heroes, this.addSkillsToHero)),
map((heroes: Hero[]) => this.mutateHeroes(heroes, this.splitName))
);
}
getHero(id): Observable<Hero> {
return this.http.get<Hero>(this.heroesUrl + "/" + id).pipe(
map((hero: Hero) => this.addSkillsToHero(hero)),
map((hero: Hero) => this.splitName(hero))
);
}
private mutateHeroes(heroes: Hero[], mutator) {
heroes.forEach((hero: Hero) => {
hero = mutator(hero);
});
return heroes;
}
private splitName(hero: Hero) {
let heroNames: string[] = hero.name.split(" ");
hero.firstname = heroNames.splice(0, 1).join(" ");
hero.lastname = heroNames.splice(heroNames.length - 1, 1).join(" ");
hero.middlename = heroNames.join(" ");
return hero;
}
private addSkillsToHero(hero: Hero) {
hero.skills = this.getSkills(Math.ceil(Math.random() * 10));
return hero;
}
private getSkills(count: number): string[] {
let skills: string[] = [];
let i;
for (i = 0; i < count; i++) {
skills.push(this.getRandomSkill());
}
return skills;
}
private getRandomSkill(): string {
return SKILL_TAGS[Math.floor(Math.random() * SKILL_TAGS.length)];
}
// [...]
}
The catchError() of the Observable(s) return: Cannot read property 'getSkills' of undefined
I am suspecting that the mutator does not get called inside the class scope, and cant be found therefore.
How would I do such a thing in JS?
The whole project can be inspected at: