Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){
        this.resetScreens();
        this.editJobScreen1 = true;
    if(this.selectedLocations.length > 0){
        this.locationService.getLocationByInput({
          maxResultCount:16,
          skipCount: 0
        }).subscribe((ele)=>{
          this.Regions = ele.items;
          this.Regions.forEach((element) => {
          this.HiringRegionMapComponent.list.push(element.id);
        });
        })
        for(let i=0;i<this.selectedLocations.length;i++){
          setTimeout(() => {
            this.HiringRegionMapComponent?.addColor(this.selectedLocations[i].id);
          }, 150);
        }

      }
    }

Concern

An issue arises when attempting to color regions on an SVG map based on their ID. This problem occurs within a specific function triggered by the user pressing the back button. The use of setTimeOut() appears to resolve the issue, but occasionally leads to the function addColor() breaking (approximately 2 out of 20 times). A stable solution is sought to avoid these intermittent failures.

Anticipated Solution

Technologies:

  1. Angular (11.0.0)
  2. .NET Core (5.0)

A viable approach to address the predicament

Answer №1

It seems like the issue may be due to nearing the end of Angular's context.

Instead of relying on setTimeout or other methods that are monkey-patched for change detection, consider using NgZone for better control. Alternatively, triggering the change detection manually can also be a more effective approach. Lastly, it's advisable to stay within Angular's context as much as possible to avoid potential problems.

// NgZone

constructor(private zone: NgZone) {}

// ...

this.zone.run(() => {
  if (i == 1) 
  // ...
});

// Change detector

constructor(private cdRef: ChangeDetectorRef) {}

// ...

for(let i=0;i<this.selectedLocations.length;i++) {
  // ...
}
this.cdRef.detectChanges();

Answer №2

It seems like your approach may not work effectively if the response time of your service is slower than the designated timeout period.
Consider moving the for loop inside the subscribe function to ensure smoother execution.

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

Why am I encountering this issue? The "map" property does not appear to be available for the type "Observable<boolean>"

I have been working on an Angular project where I am utilizing an AuthGuard class to prevent unauthorized access to protected pages. Despite following an online course, I encountered the following issue: import { CanActivate, ActivatedRouteSnapshot, Router ...

retrieving and presenting information stored in a Firebase repository

I am currently working on retrieving data from a firebase database and storing it in an array called courses that I have declared within my class. Here's the code I have so far: import { AngularFireDatabase, AngularFireList } from 'angularfire2 ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

Creating components through the command line while managing multiple projects using Angular CLI 6

Currently, I am utilizing the most recent Angular CLI version (v6). Within my codebase resides a collection of applications housed within the projects directory. My objective is to create and organize various modules and components within these projects v ...

Encountering an Error When Trying to Run Npm Install in React-Native

I encountered an issue while trying to perform an npm install on my project, so I deleted the node modules folder in order to reinstall it. However, even after running npm install in the appropriate directory, I continued to face numerous errors in my term ...

What's the issue with conducting a unit test on a component that has dependencies with further dependencies?

I am experiencing an annoying error that seems to be my mistake and I cannot figure out how to resolve it. The issue lies within a simple component which serves as a top-bar element in my web application. This component has only one dependency, the UserSe ...

Error: `__WEBPACK_IMPORTED_MODULE_1_signature_pad__` does not function as a constructor

I recently discovered the angular2-signature-pad library for capturing signatures in my Angular project. I attempted to integrate the library using the following steps: // in .module.ts file import {SignaturePadModule} from "angular2-signature-pad"; @NgMo ...

Angular encountered an error while attempting to manage a base service that was not defined

My service involves extending a base service to handle error data effectively. For instance import { CurrentUserService } from './current-user.service'; import { CONFIG } from './../shared/base-urls'; import { BaseServiceService } fro ...

I find that ChangeDetectionStrategy.OnPush does not function as anticipated

Exploring the performance boost of ChangeDetectionStrategy.OnPush in Angular 2 (detailed here) has been my recent focus. However, I've encountered an interesting scenario. In my code, I have the parent component AppComponent: @Component({ selector ...

Troubleshooting: Angular 2 property binding animations not functioning as expected

I'm attempting to create a fade-in animation for a div element. Here is the code snippet: import { Component, trigger, state, style, transition, animate, keyframes, group } from '@angular/core'; @Component( ...

Why am I unable to apply the keyof operator from one type to another type, even though both types have identical keys defined but different value types?

Consider this code snippet. I am encountering a TypeScript error specifically on the last compat[k] line with the following error message: Type 'keyof T' cannot be used to index type 'Partial<CompatType>' export type KeysOfType ...

The MatTableDataSource provides a promise that includes approximately 7000 rows of data

When attempting to load a large amount of data into a MatTableDataSource, I am facing an issue. I would like to display a loader until the data is fully set, but I am unsure of when that happens. I attempted to use a promise like this: return new Promise(r ...

The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below: <input matInput #inputSearch> @ViewChild('inputSearch', { static: false }) input: ElementRef; fromEvent(th ...

What is the best way to allow a C# Web API method to be accessed from any origin?

My C# Web API includes the following method: public JsonResult PlanItems(string sessionId) { Response.Headers.Add("Access-Control-Allow-Origin", "*"); DTDBDataService svc = new DTDBDataService(_db); VM.PlanItems = svc.GetPla ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

(Angular 6) To make it function properly, you must click the button twice

I am facing an issue with populating a form using database information. I have created a method that is called in NgOnInit, but it seems to require being called twice for it to work properly. This is the method: ngOnInit() { this.typeForm = this.for ...

The @Input() property within an Angular component is producing an empty array as its result

I have a calendar component that has a data property marked as @Input(): import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-calendar', templateUrl: './calendar.comp ...

"Exploring the process of extracting data from a JSON URL using NextJS, TypeScript, and presenting the

After tirelessly searching for a solution, I found myself unable to reach a concrete conclusion. I was able to import { useRouter } from next/router and successfully parse a local JSON file, but my goal is to parse a JSON object from a URL. One example of ...

Is there a simple method to eliminate devDependencies from the ultimate package using esbuild?

My current challenge involves using esbuild to package my lambda functions. However, during the build generation for deployment, I encounter an alert indicating that the package size exceeds the limit, as shown in the image below. File too large In explo ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...