The question is published on by Tutorial Guruji team.
I have an array of userIds. For example: ['jd', 'abc']
. And I’m looping through the userIds to fetch for full names through api. In the end, I want to turn above array into [ {userId: 'jd', name: 'John Doe"}, {userId: 'abc', name: 'full name'}]
.
code below: I tried returning arrEnriched
inside subscribe and also tried returning outside the forkjoinm. Both didn’t work as expected.
getUserObj(arr){ const arrEnriched = []; forkJoin(arr.map((item)=> { return this.userService.getUserName(item).pipe(pluck('name')); })).subscribe( (arrayOfHits)=>{ const names = arrayOfHits.map(...); // transform data arrEnriched = names.map(...); // map from full name to object console.log(arrEnriched); // as expected here //return arrEnriched; }); // return arrEnriched; }
And then I’m trying to use this function in my ngOnInit()
ngOnInit(){ this.childOneComponent.users = this.getUserObj(this.arrUsers); this.childTwoComponent.users = this.getUserObj(this.anotherArrUsers); }
Thanks.
Answer
The function getUserObj()
is asynchronous. You cannot return data from it synchronously. You could instead return the observable and subscribe to it where the data is required. Try the following
getUserObj(arr): Observable<any> { return forkJoin(arr.map((item) => { return this.userService.getUserName(item).pipe(pluck('name')); })).pipe( map(arrayOfHits => { const names = arrayOfHits.map(...); // transform data return names.map(...); // map from full name to object }) ); } ngOnInit() { this.getUserObj(this.arrUsers).subscribe((arrEnriched) => { this.childOneComponent.users = arrEnriched; }); this.getUserObj(this.anotherArrUsers).subscribe((arrEnriched) => { this.childTwoComponent.users = arrEnriched; }); }
You could find more information about how to access async data here.