Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is:

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

Code Snippet

      if (this.newsShow != null) {
        if (this.glbNews.nIds == null) { 
            this.setNewsProvider(); //This works fine
        }
        else {
            if (this.newsShow.EmpLst == null) { 
                this.setNewsProvider(); // This also works
            }
            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(); // Error occurs here: "Cannot read properties of undefined (reading 'setNewsProvider')"
                            }
                        })
                    }
                    else {
                       //Additional code goes here
                        })
                    }
                }
              

            }
        }
    }

Answer №1

When inside the forEach loop, a function is entered with its own unique this value. To circumvent this issue, JavaScript programmers often used to write

const that = this;

at the beginning and then utilize that.setNewsProvider() so that a more locally scoped this doesn't overwrite it. Alternatively, using an arrow function can avoid the problem as they do not have their own local this value.

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

Answer №2

You opted for a standard function function() {} instead of an arrow function, denoted as () => {}. While regular functions do not grasp the concept of the this keyword, arrow functions have that capability.

The reason you encountered the error message

Cannot read properties of undefined
is because the this within the function(value) does not reference the same object as the one outside it when using a normal function. Consequently, any attributes or methods associated with this will not be accessible from within the regular function.

To resolve this issue, switch to an arrow function, like so:

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

If you want a more in-depth explanation on the distinctions between these two types of functions, check out this post:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embed a div element within a content-editable area

Is there a way to add a div with text to a contenteditable element and automatically select the text between the div tags after inserting the div? div.innerHTML +='<div id="id">selecttext</div>' I have tried this method, but it does ...

Stop the interval when hovering and start the interval when moving the mouse away

I've managed to create a carousel that automatically slides every 5 seconds, with manual buttons to navigate the slides. My goal is to pause the scrolling when the mouse hovers over a slide and resume once it's no longer hovered. Currently, my s ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

Using AngularJS to access the properties of a header within a $http request

As I navigate through the github API's pagination documentation, I am attempting to retrieve event items and extract the Link header (as recommended) in order to construct the pagination. However, I am facing difficulty in understanding how to work wi ...

Dividing HTML and JavaScript using Vue

Is there a way to separate HTML from data/methods in VueJS to avoid having one long file with both? I tried moving the contents of my <script> section into a new file called "methods.js" and importing it using: <script src="methods.js"> Note ...

Is there a way to display the background when the popover is visible and hide it when the popover is hidden?

How do I make the backdrop appear when the popover is displayed, and disappear when the popover is closed? $(function(){ var content = '<button class="btn btn-sm btn-default" onclick="location.href=\'/billing/\'">Pay Now ...

Rearrange the li elements within multiple ul lists using JavaScript

Is there a way to reorder multiple ul-lists on my website using JavaScript? An example of the lists may be as follows: $(document).ready(function() { var ul = $('ul.filelist'); for (let u = 0; u < ul.length; u++) { const element = ul[ ...

Is it possible to send array data in a jQuery AJAX call using the GET method?

Is there a way to pass a JavaScript array as a parameter in an AJAX GET request? I am currently dealing with an API call and have a method that requires three parameters, with the third one being an array. ...

Having trouble with Next.js 13 GitHub OAuth integration - it keeps redirecting me to Discord instead of signing me in

There's a perplexing issue troubling my application... The implementation of OAuth 2 with GitHub, Discord, and Google is causing some trouble. While Google and Discord authentication works smoothly, attempting to sign in via GitHub redirects me to Di ...

The functionality of jQuery's $.inArray does not seem to be compatible with ASCII characters

I've demonstrated the issue in this jsfiddle. The scenario involves two black coins - when one black coin is placed on another, it should trigger an alert saying "can't kill your own kind" and return the coins to their original positions. However ...

Saving game data from local storage to populate the player leaderboard

I have successfully developed a game in which users can play and their scores are stored locally. However, I am facing a challenge in figuring out how to showcase the scores of all users in a table on the Rankings page. Player Ranking Page <?php inclu ...

"Adding a new and unique document to Meteor's MongoDB collection

Currently, I have a simple Tags Collection in Meteor where I check for duplicate Tag documents before inserting: var existingTag = Tags.findOne({name: "userInput"}) If the existingTag is undefined, then I proceed with the insertion. However, I am wonderi ...

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

Place API for Google Maps

I have been utilizing the Google Place API in my code, which has been working flawlessly. However, I encountered an issue when refreshing the page after a period of time, where Firebug displayed the error message: google.maps.event is undefined. Upon furt ...

Typescript mistakenly infers the wrong type: TS2339 error - it says that property 'selected' is not found on type 'string'

When examining the code snippet below, Typescript initially infers a type string for the inner element type of the values array. However, it subsequently raises an error indicating that string does not have the property "selected". let item = { values: [{ ...

The combination of Inline CSS and Bootstrap classes does not seem to be functioning properly

I'm new to web design and currently working on a website project. My concept involves hiding the #login-box when the user clicks on the login button, and displaying another element (.dashboard) in its place. Initially, I set the .dashboard class to ha ...

Is there a Javascript library available that can generate calendar links for Google, Yahoo, Outlook, and iCal?

I recently came across a sleek and professional web page widget that includes links (for example, and meetup.com). Could someone assist me in finding the library responsible for creating these links? I explored the discussion on Need a service that build ...