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
JavaScript
x
32
32
1
if (this.newsShow != null) {
2
if (this.glbNews.nIds == null) {
3
this.setNewsProvider(); //Accessible Here
4
}
5
else {
6
if (this.newsShow.EmpLst == null) {
7
this.setNewsProvider(); // Accessible Here
8
}
9
else {
10
11
if (this.newsShow.LCL == "X300") {
12
if (this.newsShow.MXD == "N300") {
13
14
var prd1 = this.newsShow.ProducerChk;
15
16
this.glbNews.PrdNcc.forEach(function (value) {
17
if (value == prd1) {
18
this.setNewsProvider(); //Un accessible here.. "Cannot read properties of undefined (reading 'setNewsProvider')"
19
}
20
})
21
}
22
else {
23
//Some code here
24
})
25
}
26
}
27
28
29
}
30
}
31
}
32
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
JavaScript
1
2
1
const that = this;
2
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.
JavaScript
1
6
1
this.glbNews.PrdNcc.forEach((value) => {
2
if (value == prd1) {
3
this.setNewsProvider();
4
}
5
})
6