1

I am using Angular and call another function that makes an api call to check something. When I call the function, the this inside it is undefined!? why would this be? and how do I fix it? is my arrow function call incorrect?

This is the function that is calling the arrowFunc

onProductChanged(event) {
  this.arrowFunc(hasRangeConfigurations => {
    console.log("do something");
  })
}

This the the function that the above calls, the "this" is undefined in the const declaration at this point, but in the above it is a reference to my angular component.

arrowFunc(action: (hasRangeConfigurations: boolean) => void) {
    const criteria = {
        brandId: this.marketingRange?.brand?.id,
        pageNumber: 1,
        pageSize: 1,
    } as Myresults
    
    // extra code here
});

Interestingly this does exist outside the const but inside the const it is undefined!?

-- UPDATE My Solution--

Well before you know it someone deletes your question and forwards you to something else that is confusing.

As I cant ask a legitimate question as it gets deleted, I solved it this way, just assigning this to self (like I had done back in the jquery/javascript days) I dont know if this is the best solution, but hey hoo!

arrowFunc(action: (hasRangeConfigurations: boolean) => void) {
        const self = this;
        const criteria = {
            brandId: self.marketingRange?.brand?.id,
            pageNumber: 1,
            pageSize: 1,
        } as Myresults
        
        // extra code here
    });
Andrew
  • 2,571
  • 2
  • 31
  • 56
  • 1
    if this in arrowFunc is undefined then add this to your constructor ... this.arrowFunc = this.arrowFunc.bind(this) ... this means that the this in arrowFunc will always be the class instance this ... no more self ^^ – danday74 Sep 10 '21 at 21:14
  • 1
    Thanks for this, appreciate the info, thought I replied but the comment has gone! – Andrew Sep 13 '21 at 07:32

0 Answers0