0

In my code i iterate through nameArr. Inside foreach loop i call find() method from encjaService. I want to set result of calling find() method into encja1 variable. Right now when i try to declare encja1 variable in this way and in next line i try to write log on console with this.encja1.id value i get undefined as a result.

My test() method inside component file:

test(nameArr: IName[]) {
    this.names = nameArr;
    nameArr.forEach(function(item, index) {           
        console.log('TEST (item.encjaId)=>' + (item.encjaId));
        this.encja1 = this.encjaService.find(item.encjaId).subscribe((res: HttpResponse<IEncja>) => res.body);
        console.log('TEST (encja.id)=>' + (this.encja1.id));
        console.log('TEST (encja.type)=>' + (this.encja1.type));
        const element = { lp: index + 1,
            oid: item.encjaId,
            lastName: item.wholeName,
            match: item.matchedAmount + '/' + item.encjasAmount,
            description: [{name: 'adam', symbol: 'a'}]
        };
        ELEMENT_DATA.push(element);
    }, this);
}

My find() method inside encjaService:

find(id: number): Observable<EntityResponseType> {
    return this.http
        .get<IEncja>(`${this.resourceUrl}/${id}`, { observe: 'response' })
        .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}

**Question: How to set result of calling find() method into encja1 variable? **

John Doe
  • 319
  • 2
  • 5
  • 24
  • Try making the test function async Then modify your code on line 5 to wait for the observable to return a value before continuing execution this.encja1 = await this.encjaService.find(item.encjaId).subscribe((res: HttpResponse) => res.body); – Kisinga Feb 28 '19 at 22:05
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Feb 28 '19 at 22:09
  • Try defining the callback as an arrow function: `nameArr.forEach((item, index) => {...})`. – ConnorsFan Feb 28 '19 at 22:10

0 Answers0