What is causing Angular services to malfunction when used within setTimeout and setInterval functions?

manage-tasks.component.html

<p>manage-tasks works!</p>
<form #taskForm="ngForm">
    <input type="text" name="task_name" palceholder="Task Name" [(ngModel)]="task_service.selected_task.name">
    <input type="text" name="description" palceholder="describe" [(ngModel)]="task_service.selected_task.description">
    
</form>

manage-tasks.component.ts

import { Component, OnInit } from '@angular/core';
import {NgForm} from '@angular/forms'
import {TaskService} from '../shared/task.service';
import {Task} from '../shared/task';

@Component({
  selector: 'app-manage-tasks',
  templateUrl: './manage-tasks.component.html',
  styleUrls: ['./manage-tasks.component.css'],
  providers:[TaskService]
})
export class ManageTasksComponent implements OnInit {

  constructor(public task_service : TaskService) { }
  
  
  ngOnInit(): void {
    console.log(' in ngOnInit function ');
    // Checking condition using setInterval
    this.task_service.selected_task={
      name : "",
      description : ""
    };

   
   console.log(this.task_service.selected_task)
     let timerId  = setInterval(function(){
       console.log(this.task_service.selected_task);
       if(this.task_service.selected_task.name!="" && this.task_service.selected_task.description!=""){
         console.log(this.task_service.selected_task);
         clearTimeout(timerId);
       }
     },100);
  }

}

shared\task.ts

export class Task {

    name : String;
    description : String;
    
}

shared\task.service.ts

import { Injectable } from '@angular/core';

import  {Task} from './task';

@Injectable({
  providedIn: 'root'
})
export class TaskService {
   
  selected_task : Task;
  tasks : Task[]=[];

  constructor() { }
}

Setting up functions to run when form fields are filled out completely, without a submit button. Using setInterval to check the task_service.selected_task fields and perform operations when all fields are not empty strings. Encountering an error within the setInterval stating

Cannot read property 'selected_task' of undefined
. As a beginner in web development, struggling to identify the cause of this error.

Answer №1

Here is a possible solution to grasp the problem:

const self = this;
const timerId  = setInterval(function(){
       console.log(self.todo_service.selected_todo);
       if(self.todo_service.selected_todo.name !== "" && self.todo_service.selected_todo.description !== ""){
         console.log(self.todo_service.selected_todo);
         clearTimeout(timerId);
       }
     },100);

Alternatively, you can opt for a more sophisticated approach like this:

const timerId  = setInterval(() => {
       console.log(this.todo_service.selected_todo);
       if(this.todo_service.selected_todo.name !== "" && this.todo_service.selected_todo.description !== ""){
         console.log(this.todo_service.selected_todo);
         clearTimeout(timerId);
       }
     },100);

To understand why this does not refer to your class instance when used inside the setInterval function and other callbacks, please refer to this documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#As_an_object_method

The behavior of a function's this keyword in JavaScript differs from that in other languages. It also varies between strict mode and non-strict mode.

In most scenarios, the value of this is determined by how a function is invoked (runtime binding). It cannot be set through assignment during execution, and it may change each time the function is called. ES5 introduced the bind() method to specify the value of a function's this regardless of its invocation context.

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

Embracing right-to-left (RTL) languages

I am looking to create a website that can support both left-to-right (LTR) and right-to-left (RTL) languages seamlessly. My goal is to have the text direction switch automatically to RTL if the content is in an RTL language. Additionally, I want the input ...

Node/Express unexpectedly returning string instead of Array after parsing JSON file

Having difficulty parsing an empty (stringified) Array from a JSON file. Instead of returning an empty array, I am receiving a string. The initial set up of my JSON file is: "[]" I am storing the parsed data in a variable using File System let parsedOb ...

Executing usemin and useminPrepare on various targets is made possible by Grunt

According to the usemin issues, it seems that the latest version of usemin and useminPrepare now support multiple targets: Updates related to multiple targets in useminPrepare: pull#162 pull#206 New features for usemin support: Multiple targets A ...

Struggling to achieve desired outcome with Node.js and MongoDB when utilizing promises inside a loop

Being new to nodejs and mongodb, I find it really confusing to work with promises in a loop within nodejs as a beginner. I need the final array or object that will be returned by the then() function. Can someone please help me correct this issue? Below i ...

Tips on removing either the date or time when input type date and input type time share the same ng-model

In my Ionic app built with AngularJS, I have a form where the date and time are displayed separately but share the same data-ng-model: <input type="date" id ="actualVisitDate" data-ng-model="actualVisitDate" required> <input type="time" id ="actu ...

Attempting to establish a login system using MongoDB

I am currently working on a function to verify user login details entered in a form and compare them with data stored in MongoDB, such as email and password. However, the function seems to be malfunctioning. The expected behavior is that when a user ente ...

Angular - Implementing an Object Mapping Feature

Looking to dynamically generate parameter objects in Angular with a structure like this: [ password: {type: 'String', required: true, value: 'apassword'}, someRandomParam: {type: 'Integer', required: false, value:3} ] ...

Extracting information from XML and showcasing it in an HTML format

My current setup includes two hard-coded boxes from line 18 to line 70 in the HTML section. Now, I have an .XML file containing: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <collection> <beanRepresentation> <beanRepId> ...

Vue.js having compatibility issues with Semantic UI dropdown feature

I have recently started exploring Vue.js and I must say, I really enjoy using Semantic UI for my projects. In Semantic UI, dropdowns need to be initialized using the dropdown() function in semantic.js. This function generates a visually appealing HTML str ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Unable to modify text color after implementing mat-sort-header in Angular Datatable

My current setup involves using an Angular data table to display data. I recently added the mat-sort-header functionality, which allowed me to change the font color of the header text. Below is a breakdown of my code: <section id="main-content" ...

Click on the button without any reaction

I'm having trouble with the button. When I click on the button with ng-click="goSearchTitle()", nothing happens. Any idea why it's not working? <body ng-app="myapp"> <div ng-contoller="searchbyTitle"> <h3>Sea ...

Issue: Unable to locate dependencies for modules Vite and react

Struggling to develop a react app using vite and encountering the following error message: Error: Failed to scan for dependencies from entries: C:/Users/User/Desktop/responsive-app/index.html The path to my project, I am using windows for this specific p ...

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

Utilize jQuery to toggle and swap between multiple classes

I am looking to implement a feature where clicking on certain cells will add and switch classes, similar to a calendar schedule. I attempted the code sample below, but it did not successfully toggle each class. The desired outcome is to switch classes li ...

The execution of res.sendFile has been terminated, redirecting me to localhost:XXXX/?

In my application, I have set up a route that is being accessed, confirmed by the console.logs. However, the issue lies with the res.sendFile function at the end, as it is not directing me to the intended location. Instead, it redirects me to localhost:XXX ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...

Utilize Angular to transform a JSON string into HTML text featuring organized bullet points

I am currently working on a project using Angular and I need to display some data from a JSON file on a webpage. The issue I am facing is that the message is quite lengthy, and I would like it to be presented in bulleted points. "messageToDisplay" ...

Utilize ngSwitch in Angular 5 for dynamically rendering either text or textarea content

My goal is to utilize ngSwitch in order to dynamically display either text or a text area based on the Format Type ID. Each question should either display a text area or an input text field. However, currently, the text area is being displayed for every F ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...