Skip to content
Advertisement

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
                        })
                    }
                }
              

            }
        }
    }

Advertisement

Answer

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(); 
  }
})
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement