issue with global variable not functioning properly within a sub-function in Angular 7

I have a question that needs clarification

import { Component, OnInit,ViewChild,ElementRef  } from '@angular/core';
import {Http,Headers} from "@angular/http";
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, Subscription } from 'rxjs';
import { map, filter, debounceTime, tap, switchAll, count } from 'rxjs/operators';
@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {
  constructor(private http:Http) {

   }
   @ViewChild('abcde') abcde: ElementRef;
   private typeTerm = new Subject<string>();
   public result:string="";
}

Also Involves Function Call variable result

fTyping(a){
  this.result="abcd"; //It is working
  if(this.timeout){ clearTimeout(this.timeout);}
  this.timeout = setTimeout(function() {
    this.result="efgh"; //**Not Working**
    const url="http://localhost:81/api/films/GetFilms",body=JSON.stringify({username:"admin",password:"admin",page:1,"search":a,sort:this.txtSort});
    const requestHeader = new Headers({ 'Content-Type': 'application/json' });
    http1.post(url,body,{ headers : requestHeader }).toPromise().then(res=>{
    temp=res.json();
    console.log(res.json().length);
    this.isLoading=false;
    if(res.json().length<10){
      this.isData=false;
    }
    else
      this.isData=true;
    }).catch(x=>{
      this.result=JSON.stringify({Name:"No data",Title:"No Data",Manufacture:"No Data",Country:"No Data"});
      this.isLoading=false;
      this.isData=false;
    });
  },500);
}

Issue at hand: Why does the variable this.result not work within the function setTimeout? Is there a solution to make it work inside the setTimeout function?

Answer №1

setTimeout function creates its own scope inside, causing 'this' to not work as expected. To resolve this issue, you can save a reference of 'this' in another variable.

var that=this;
this.timeout = setTimeout(function() {
    that.result="efgh"; //use that
  },500);

Alternatively, you can use an arrow function which does not create its own 'this' scope.

setTimeout(() => {
 this.result="efgh";
},500)

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

Tips on toggling the visibility of an element in Angular 4

This is my unique html element: <ng-container> <span *ngIf="row.messageText && row.messageText.length >= 30 && expanded">{{row.messageText.substr(0, 25)}} <span>more</span> </span> ...

Obtain the firebase object using Angular framework

Hey there, I've been working on retrieving a Firebase object using Angular and have successfully achieved that. However, I'm now faced with the challenge of how to navigate deeper into the data that is being returned (check out the images linked ...

Repetitive execution of Angular service function upon route change

In my Angular 8 project, there is a service function responsible for copying data. However, I encountered an issue where if I copy the data on a page, navigate to another page, and then return to the original page to copy the data again, it ends up duplica ...

Angular: Understanding the intricacies of HTTP calls in ngOnInit versus click events (potentially related to caching mechanisms)

Within my Angular application, I have a basic service configured to communicate with the server. The service has been injected into a component. Interestingly, when I directly call one of its methods inside the ngOnInit() method of the component, everythin ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction: A -> B -> C To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code: In Component C: private ...

How can you exclude templates in an Angular 7 CLI build to incorporate MVC views?

Currently, I am exploring the latest updates in Angular (7+) and CLI. After completing parts of the 'Tour of Heroes' tutorial, I have been able to use 'ng build' to generate production files. However, a key requirement for me is using ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Unable to invoke Angular function from within jQuery

I am currently using the angular full calendar plugin and have successfully added a context menu in the event render function. The context menu is functioning properly, but I am facing an issue where I want to call an Angular function when a context menu i ...

What is the cause of the error message "property 'map' is undefined"?

I am currently working on a service that looks like this: public getUsers() { return this.httpClient.get(environment.BASE_URL + `api/all`); } In my component, I have implemented the ngx-bootstrap table to display the user data. import { Component, OnI ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Believed I had a clear understanding of the situation

Within the following code snippet, I am utilizing a service (Angular) to extract text using a fileReader and implementing a promise for the asynchronous part. However, I am encountering an issue that appears to be related to scope, which is causing confusi ...

Sending a post request to an Express.js API from a different device

I currently have a server running on localhost:3000, with my app.js set up to utilize the angular router. When attempting to access localhost:3000 in my browser (for example: app.use('/', express.static(path.join(__dirname, '/dist/Client&apo ...

Angular 11 Working with template-driven model within a directive

My currency directive in Angular 8.2 formats currency fields for users by using the following code: <input [(ngModel)]="currentEmployment.monthlyIncome" currency> @Directive({ selector: '[ngModel][currency]', providers: [Curr ...

How to Generate a Collection of Textfields in Angular 4

My challenge involves working with an array object that receives input from a textfield. I am looking to create a clean design where only one textfield is initially displayed, along with a '+' button next to it. When the user enters information i ...

Why is the ngx slick carousel not functioning properly within the ngx-bootstrap accordion in Angular 7?

I am trying to incorporate the ngx-slick-carousel inside an ngx-bootstrap accordion and tabs. The tabs are located within the accordion, but when I try to add the carousel outside of the accordion, it works fine. How can I successfully add it inside the ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...