【问题标题】:Javascript/Angular: timeout wrapped in function not workink with boolean valueJavascript/Angular:包裹在函数中的超时不适用于布尔值
【发布时间】:2019-07-17 12:44:42
【问题描述】:

在视图中我有这种情况:

    <h3 *ngIf="show">{{users.result}}</h3>

在我的 TypeScript 逻辑中:

show=false; <----as a property

还有以下功能:

timeOut(seconds: number, value:boolean) {
   value = true;      
    setTimeout(
      function() {
        value = false;
      }.bind(this),
      seconds
    );
  }

但是当我调用它时,像这样:

console.log(this.timeOut(3000, this.show));

属性“this.show”未定义,但作为参数传递的秒数有效。我遗漏了一些东西,我不知道是什么...有人可以帮忙吗?

【问题讨论】:

  • 您想在seconds 之后切换show 属性吗?
  • console.log(this.timeOut(3000, this.show)); 应该返回 undefined 因为this.timeOut 不返回任何内容

标签: javascript angular timeout


【解决方案1】:

如我所见:

  • 首先控制台日志记录 函数调用没有结果
  • 当您传递 布尔值 到函数参数时,它被复制,所以当您更改函数内部的值,它不影响外部变量/字段。
  • 这是一个非常专业的用例,因此您无需将其提取到不同的函数中。

我的建议 - 只需将带有 箭头函数setTimeout 调用放入某些组件的方法中,例如 ngAfterViewInit事件处理程序方法强>:

ngAfterViewInit() {
   setTimeout(() => this.show = true, 3000)
}

希望对您有所帮助。

【讨论】:

  • 像这样:`ngAfterViewInit(): void{ this.timeOut(3000, () => this.show = true); }´ 都变红了
  • 应该是ngAfterViewInit(): void{ setTimeout(() =&gt; this.show = true, 3000); },你应该调用原生的setTimeout函数,我混淆了参数顺序,更新了一个答案
  • 现在它说:“'3000' 类型的参数不能分配给'TimerHandler' 类型的参数。”
  • 更改 3000() =&gt; this.show = true 参数顺序,如更新的答案
  • 没问题,我很高兴它有帮助!
猜你喜欢
  • 1970-01-01
  • 2018-12-05
  • 2021-10-16
  • 2016-10-23
  • 2018-02-22
  • 2011-01-17
  • 1970-01-01
  • 2019-06-06
  • 1970-01-01
相关资源
最近更新 更多