Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document.

The function is executed in a loop up to a value of 5.

However, even though the function runs 5 times, the value of 'i' always reflects the last value. The value is continuously printed outside the function.

user="manjoola";

private saveToken(user, token): void {      
        var i:number=0;
        var user_document:string=user;

    for(i=0;i<5;i++)
      {
        user_document=user+i;
        console.log(user_document);
  this.firestore.doc(`pushnotifications/${user_document}`).ref.get().then((documentSnapshot) => {   

    console.log(documentSnapshot.exists);
    if(documentSnapshot.exists)
    {    

    console.log('It exists'+user+i);
    snapshot=true;    
      }

    else
    {
      this.firestore.collection(`pushnotifications`).doc(`${user_document}`).set({'authtoken': user, 'fcmtoken': token});
      console.log('Does not exists'+user+i);
      snapshot=false;

    }
    snapshot=false;
  }).catch(function (error)
  {
    console.log("Error getting document:", error);
  }
  ); 

  console.log(i);

}
}

Console log:

manjoola0
messaging.service.ts:137 0
messaging.service.ts:112 manjoola1
messaging.service.ts:137 1
messaging.service.ts:112 manjoola2
messaging.service.ts:137 2
messaging.service.ts:112 manjoola3
messaging.service.ts:137 3
messaging.service.ts:112 manjoola4
messaging.service.ts:137 4
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 false
messaging.service.ts:126 Does not existsmanjoola5
messaging.service.ts:115 true
messaging.service.ts:119 It existsmanjoola5

Answer №1

Modify this: for(i=0;i<5;i++)

to this: for(let i=0; i<5; i++)

The change above will scope the variable i within the block instead of the function, which should resolve the issue you are facing.

To successfully implement the above change, make sure to delete this line as well: var i:number=0; - this is to avoid a "variable has already been declared error" (as you are initializing i within the for statement)

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

Struggling with making updates to an interface through declaration merging

I am encountering challenges with implementing declaration merging on an interface from a library that I created. An example illustrating the issue using StackBlitz can be viewed here: https://stackblitz.com/edit/typescript-qxvrte (issues persist in both ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

How can a TypeScript function be used to retrieve a string (or JSON object)?

When attempting to retrieve data from a web API using TypeScript and return the JSON object, encountering an error has left me puzzled. Inside my function, I can successfully display the fetched data on the console, but when I try to return it with return ...

Using optional chaining with TypeScript types

I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example: MyQuery['system']['error ...

Learn how to extract precise information from a JSON array by utilizing Angular 6

After making a GET request in Angular 6, I successfully retrieved data from a JSON array. Now, I have this JSON data as an example and my goal is to find the team(s) that employee "TEST4KRWN" is part of. Can anyone guide me on how to write a JSON query us ...

The search button in the ngx-pagination StartDate and EndDate Search Filter is unresponsive

Working with Angular-14 and ASP.Net Core-6 Web API to consume an endpoint and handle JSON responses. An example of the endpoint URL without parameters: https://localhost/MyApp/api/v1/all-merchants And when parameters are included: https://localhost/MyApp ...

What is the best way to update queryParams without activating subscribe functions?

Hello, I am currently in the process of developing an angular app with multiple routes. When navigating to a specific page, the queryParams trigger the subscribe function. While on the page, I need to be able to change the queryParams without triggering ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

What is the process for creating a coverage report for a TypeScript extension in vscode?

It appears that generating coverage reports with coveralls is not feasible for a VSCode extension built with TypeScript. Currently, I am incorporating test cases into our project https://github.com/PicGo/vs-picgo/pull/42. Despite exploring various methods ...

Tips for arranging, categorizing, and separating the array in alphabetical order using Angular 2+

I am looking to organize the buttons' content alphabetically into groups A-H, I-Q, and R-Z. The code I'm using is in Angular2+. https://i.sstatic.net/pPCBO.png My array: this.dropdownList = [ { item_text: 'Organisation' }, ...

Is it possible to record the attributes within an interface in TypeScript?

Imagine I have the following scenario: interface Validator { validate: (value: string) => boolean; errorMessage: string; } interface EditDialogField { label: string; prop: string; required?: boolean; type: 'input'; validators?: ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

What is the best way to limit the type of the second argument based on the type of the

Within the tutorial Exploring How to Extract Parameter Types from String Literal Types Using TypeScript, a fascinating problem is presented without a solution. function calculate(operation, data) { if (operation === 'add') { return da ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

The issue arises from a custom Angular directive causing a NullInjectorError:StaticInjectorError in the AppModule when trying to inject MatInput into ElementRef

My Angular application is encountering a compilation error after upgrading to Angular 8. Despite updating and reinstalling the Material dependencies, the following error persists: NullInjectorError:StaticInjectorError(AppModule)[MatInput -> ElementRef] ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...