简体   繁体   English

Javascript / Angular:超时包装在具有布尔值的函数中不起作用

[英]Javascript/Angular: timeout wrapped in function not workink with boolean value

In the View I have this condition: 在视图中,我有这种情况:

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

In the TypeScript logic I have: 在TypeScript逻辑中,我有:

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

And the the following function: 和以下功能:

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

But when I call it, like this: 但是当我这样称呼它时:

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

the property `this.show´ gets undefined, but the seconds passed as argument work. 属性“ this.show”未定义,但秒作为参数起作用了。 I'm missing something and I can't figure out what... Can anyone give a help? 我丢失了一些东西,我不知道该怎么办...有人可以帮忙吗?

As i see: 如我所见:

  • First of all you console logging function call without result . 首先,您在没有结果的情况下 控制台记录 功能调用。
  • When you pass the boolean value into the function params it's being copied , so when you change the value inside the function, it doesn't affect the outside variable/field. 当您 布尔值 传递到函数参数中时,它将被复制 ,因此,当您在函数内部更改值时,它不会影响外部变量/字段。
  • This is very specialized use case, so you do not need to extract it to different function. 这是非常专业的用例,因此您无需将其提取到其他功能。

My suggestion - just put setTimeout call with arrow function into some component's method like ngAfterViewInit or in event handler method : 我的建议-只需将带有箭头功能的 setTimeout调用放到某些组件的方法(如ngAfterViewInit)中事件处理程序方法中

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

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM