Encountering an error stating "Property of undefined cannot be read" while attempting to call a function

While I can call a function without any issues, when attempting to call it within setInterval to have it run every second, an error arises: "cannot read property of undefined on the service!"

 constructor(private route: ActivatedRoute,private 
 conversationService:ConversationService) {
 }


 ngOnInit() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(
 function()
 { 
   this.conversationService.
   getTheConversation(this.receiver,this.sender).subscribe(
     data=>this.result=data)
   },1000);
 } 

Error: ERROR TypeError: Cannot read property 'getTheConversation' of undefined

Answer №1

Experiment

 initialize() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(() => { 
   this.conversationService.
   fetchConversation(this.receiver, this.sender).subscribe(
     data => this.record = data)
   }, 1000);
 } 

Utilize fat arrow notation => to uphold this scope. When defining a new function, it establishes its own this.

Answer №2

Utilizing the setInterval function involves a unique reference to an alternative this object,

To ensure proper execution, the following approach is recommended:

const newThis = this;
setInterval(
 function()
 { 
   newThis.conversationService.
   getTheConversation(newThis.receiver,newThis.sender).subscribe(
     data=>newThis.result=data)
   },1000);

For additional methods on achieving this task, explore the suggestions provided in this link

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

Unable to choose fields and options within the popup box

Interacting with jQuery: $("#type_name").click(function(){ $("body").append('<div class="modalOverlay">'); $("#add_form").fadeIn(1000); $("#first_name").val(""); $("#email").val(""); ...

How can I simulate the enter key being pressed for testing purposes using jQuery or pure JavaScript?

Is there a better method for simulating the user pressing the "Enter" key? I have tried using $(element).keypress() but it doesn't seem to capture the exact key pressed. This is specifically for unit testing purposes. ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

"Error: Unfinished string literal encountered" occurring in a TypeScript app.component.ts file in NativeScript

I've been trying to learn NativeScript through a tutorial, but I keep encountering errors. Here is an excerpt from my app.component.ts file: import { Component } from '@angular/core'; @Component ({ selector: 'my-app', temp ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...

TypeScript: Type narrowing issue when deconstructing an array within a function

I am working with an object that has a const assertion: const foo = { bar: ['a', 'b'], } as const; My objective is to create a function that can update the bar array and accurately infer the new type. I have successfully achieved th ...

The function "toggleHeightAndOpacity" cannot be accessed on this object because it is not defined

I'm attempting to invoke a variable function name, a task I have successfully accomplished many times in the past using code similar to that found here. <script type="text/javascript"> $.fn.toggleHeightAndOpacity = function(show) { ...

How can I retrieve text that is enclosed within 2 specific tags and then format the output according to my preference?

Is it possible to extract text between specific tags and format the output as desired? Are there any tools or scripts available for this task? For instance: [b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers Club Mix) [i](3:26 ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

Backbone - NestedModels - Issues with nested sets not triggering 'change' event

I have incorporated the Backbone nested plugin into my project. The way I set up my binding is as follows : var view = Backbone.View.extend({ initialize: function(params) { this.model.bind('change', _.bind(this.rerender, this)); ...

Steps for creating a link click animation with code are as follows:

How can I create a link click animation that triggers when the page is loaded? (function () { var index = 0; var boxes = $('.box1, .box2, .box3, .box4, .box5, .box6'); function start() { boxes.eq(index).addClass('animat ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

What could be the reason for this Javascript code not functioning as intended, failing to generate a random number between 1 and 3 when I click on any of the buttons

Could someone help me with generating a random number between 1 and 3 each time I click on one of the buttons (rock, paper, scissors)? I am new to programming and not sure what I'm doing wrong. <!doctype html> <html lang="en"> <head& ...

How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js. <li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." > Content </li> My goal is to apply a class to the li el ...

What is the best way to prevent labels from floating to the top when in focus?

How can I prevent the label from floating on top when focusing on a date picker using Material UI? I have tried several methods but nothing seems to work. I attempted using InputLabelProps={{ shrink: false }} but it did not resolve the issue. Here is a li ...

Angular - Array binding in view not refreshing

Within the following code snippet, the push function is utilized to transfer only the checked row from an array to another. Despite the successful execution of the push operation, the view does not reflect this update. onNextclick() { this.disable1 ...

Puppeteer: How to wait for an ajax call to complete after a navigation event

When working with my code, I encounter a situation where I need to submit a form, wait for navigation, and then submit a second form. The challenge arises because before submitting the second form, some data needs to be loaded in the form using ajax. I wa ...

Angular displays an error message and applies an invalid class when a form is submitted

I have created a form in Angular(5) using a template-driven approach. My goal is to display error messages and apply different styles to the input fields when they are invalid, especially when the form is submitted. Currently, I am able to achieve this fu ...

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

Using Dat GUI alongside Three.js to generate 3D text geometry based on user input, with real-time updates

Trying to utilize the combination of Dat GUI and Three.js to allow for user inputted text to generate 3D text geometry that updates in real time. Successfully achieved control over the x, y, and z positions, as well as displaying the text input box. Strug ...