TechGuy
TechGuy

Reputation: 4570

Unable to accessible some code in TypeScript TS

I have a simple if else code in TypeScript.But in some code unable to access it.It shows me the following error,

"Cannot read properties of undefined (reading 'setNewsProvider')"

Code

 if (this.newsShow != null) {
        if (this.glbNews.nIds == null) { 
            this.setNewsProvider(); //Accessible Here
        }
        else {
            if (this.newsShow.EmpLst == null) { 
                this.setNewsProvider(); // Accessible Here
            }
            else {

                if (this.newsShow.LCL == "X300") {
                    if (this.newsShow.MXD == "N300") {

                        var prd1 = this.newsShow.ProducerChk;

                        this.glbNews.PrdNcc.forEach(function (value) {
                            if (value == prd1) {
                                this.setNewsProvider(); //Un accessible here.. "Cannot read properties of undefined (reading 'setNewsProvider')"
                            }
                        })
                    }
                    else {
                       //Some code here
                        })
                    }
                }
              

            }
        }
    }

Upvotes: 0

Views: 122

Answers (2)

James Deacon
James Deacon

Reputation: 36

Inside the forEach loop you enter a function, the function has it's own this value. To avoid the problem, JS programmers used to often write

const that = this;

at the entry point and then use that.setNewsProvider() so that a more locally scoped this does not override it. if you use an arrow function the problem will be avoided as these do not have their own local this value.

this.glbNews.PrdNcc.forEach((value) => {
  if (value == prd1) {
    this.setNewsProvider(); 
  }
})

Upvotes: 2

Atlinx
Atlinx

Reputation: 594

You used a regular function function() {} instead of an arrow function, which is () => {}. Regular functions don't capture the this keyword, but arrow functions do.

Because this isn't captured, you get the Cannot read properties of undefined error because the this inside of the function(value) is a different this than the one outside. Any properties and functions of this would not be brought into the regular function.

The fix is to use an arrow function, ie.

...
this.glbNews.PrdNcc.forEach((value) => {
  ...
});
...

Here's a post that more thoroughly explains the differences between the two function types:

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

Upvotes: 2

Related Questions