I have a private variable called product which I initialize in the constructor. Then I have an array.forEach() in the ngOnInit. console.log shows the value I'm trying to store in product but I'm getting a 'Cannot Read Properties' of undefined on product. What am I doing wrong?
private product: string;
constructor(private service: Service) {
this.product = "";
}
ngOnInit() {
this.service.sections.forEach(function (value) {
if (this.product) {
this.product = value.Product.ShortName;
} else {
this.product = "";
}
console.log(value.Product.ShortName);
});
}
CodePudding user response:
Convert your function (value) {...}
to an arrow function
Arrow functions don't have their own bindings to this, arguments or super, and should not be used as methods.
this.service.sections.forEach((section) => {
if (this.product) {
this.product = section.Product.ShortName;
} else {
this.product = "";
}
console.log(section.Product.ShortName);
});
CodePudding user response:
@MikeOne, place an important mark.
Your problem occurs due a context error, so
the member class product
should be not referred with this
because into a traditional js function it looks to function context itself.
So assigning it to an global accessor whereas can be accessible should fix.
ngOnInit() {
var self = this
this.service.sections.forEach(function (value) {
if (self.product) {
self.product = value?.Product?.ShortName || "";
} else {
self.product = "";
}
console.log(value.Product.ShortName);
});
}
But as legacy, here a tip of how proceed if some received value into callback can be null.
So javascript throw an exception when you're trying read a property of that null, such Product
you can use a handful elvis operator ?
to avoid exceptions like that.
so your assignment should be written in this style:
this.product = value?.Product?.ShortName || null;