【问题标题】:Angular Declaring Global Variable From Within Class FunctionAngular 从类函数中声明全局变量
【发布时间】:2018-09-28 08:37:54
【问题描述】:

我只想知道如何在 Angular 5 中的类函数中创建一个全局变量。我的问题是我在一个函数中创建了一个 setInterval 变量,但是我不知道如何访问该变量以在不同的函数中执行 clearInterval(var)。有关如何解决此问题的任何建议?

这是一个解释我的问题的简单进度条,注释掉 //clearInterval(RunningTimer);是我被困的地方

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

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我认为你从错误的角度来看这个,你为什么要清除 RunningTimer,这是一个定义在范围内的变量,每次输入该函数时它都会是一个新变量,问题是你需要清除 iProgressValue 变量,所以

    替换

    //clearInterval(RunningTimer);
    

    this.iProgressValue = 0;
    

    你已经完成了。

    【讨论】:

      【解决方案2】:

      只需添加一个字段而不是局部变量:

      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";
          }
        }
      }
      

      【讨论】:

      • Titian,由于某种原因,这在 stackblitz 中有效,但在我的项目中无效。在 this.RunningTimer 上出现错误:类型“计时器”不可分配给类型“数字”
      • @Frank 将类型改为timersetInterval的隐式定义应该返回一个数字,不知道你有什么定义...
      • 这里是同样的问题:github.com/TypeStrong/atom-typescript/issues/1053 我的解决方案是添加窗口。在 setInterval 前面,同时保持类型为数字
      • @Frank 如果你在 2.8 上试试 runninTimer: ReturnType<typeof setInterval>; 但如果代码在浏览器中运行你不应该使用节点定义。
      【解决方案3】:

      为什么不创建一个提供设置和清除变量功能的服务?该服务可以注入到需要它的每个组件中。

      export class YourService{
      
            private _yourVar: yourVarDefintion;
      
            public get yourVar(): yourVarDefintion{
              return this._yourVar;
            }
      
            public set yourVar(id: yourVarDefintion) {
              this._yourVar = id;
            }
      }
      

      【讨论】:

      • 我真的不需要这么复杂的东西,嘿
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 2015-05-11
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多