0

I have the following class:

export class UIDService {

    constructor()
    {
    }

    public getDataFromResponse(response: any) {
    
        var companyArray = [];
        var searchResult = response["s:Envelope"]["s:Body"].SearchResponse.SearchResult;
    
        if (searchResult) {
            var searchResultItems = searchResult.uidEntitySearchResultItem;
            try {
                Array.isArray(searchResultItems) ? searchResultItems.forEach(function(param) {
                    companyArray.push(this.getAddress(param.organisation))
                }) : companyArray.push(this.getAddress(searchResultItems.organisation))
            }
            catch(err) {
                console.log(err);
            }
        }
        
        return companyArray;
    }

    private getAddress(org: any) {
       //Do Stuff
       //Do Stuff
       //Do Stuff
       //Do Stuff
    }
}

Which leads to the following error.

Cannot read property 'getAddress' of undefined

I know that this is lost in this context but I'm struggling to get this working. I also tried to put "this" into a instance variable in the constructor but non of my tries were successful.

Any hints to get this running?

Help is really appreciated!

  • Please share how `getDataFromResponse` is used – evolutionxbox Aug 27 '21 at 14:17
  • 2
    Your `forEach` callback is a traditional function, which means its `this` is set by how it's called. `forEach` doesn't set any particular this if you don't pass it one (as the second argument), so you get `undefined` (in strict mode). Make the callback an arrow function instead. (Or pass `this` as the second argument to `forEach`.) Or better yet, use `if`/`else` and a simple `for-of` loop. Here's that suggestion: https://pastebin.com/f6G7BNkC – T.J. Crowder Aug 27 '21 at 14:18

0 Answers0