0
votes

I would just like to know how to create a global variable from within a class function inside Angular 5. My problem is that I create a setInterval variable in one function, but then I don't know how to access that variable to do clearInterval(var) in a different function. Any advice on how to solve this problem?

Here is a simple progress bar explaining my problem, the commented out //clearInterval(RunningTimer); is where I am stuck at

https://stackblitz.com/edit/angular-y8zcio?file=app%2Fapp.component.html

3

3 Answers

1
votes

Why you don't create a service which offers a function to set and clear the variable? This service can be injected in every component where it is needed.

export class YourService{

      private _yourVar: yourVarDefintion;

      public get yourVar(): yourVarDefintion{
        return this._yourVar;
      }

      public set yourVar(id: yourVarDefintion) {
        this._yourVar = id;
      }
}
1
votes

Just add a field instead of a local variable:

export class AppComponent  {
  sStatus = "Inactive";
  iProgressMax = 100;
  iProgressValue = 0;
  private runningTimer: number
  Run() {
    this.sStatus = "Running...";
    this.runningTimer = setInterval(() => {this.Running()}, 500);
  }

  Running() {
    this.iProgressValue = this.iProgressValue + 20;

    if (this.iProgressValue >= this.iProgressMax) {
      console.log("Completed")
      clearInterval(this.runningTimer);
      this.sStatus = "Complete";
    }
  }
}
0
votes

I think you're looking at this from the wrong angle, why would you clear RunningTimer, that is a variable in a scope which is defined there, every time you enter that function it will be a new variable, the problem is that you need to clear the iProgressValue variable, so

replace

//clearInterval(RunningTimer);

with

this.iProgressValue = 0;

and you're pretty much done.