Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我的设定间隔时间似乎不起作用_Javascript_Angular - Fatal编程技术网

Javascript 我的设定间隔时间似乎不起作用

Javascript 我的设定间隔时间似乎不起作用,javascript,angular,Javascript,Angular,我是javascript和angular方面的新手。这应该是一个简单的问题,但我不知道我的代码出了什么问题。我不知道我是否有时间处理程序的正确语法。代码只显示一次时间 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-

我是javascript和angular方面的新手。这应该是一个简单的问题,但我不知道我的代码出了什么问题。我不知道我是否有时间处理程序的正确语法。代码只显示一次时间

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html',
  styleUrls: ['./hello-world.component.css']
})
export class HelloWorldComponent implements OnInit {

  dateMessage: string;

  constructor() {

  setInterval(this.time_handler, 1000); 

  //Method 1: This works    
  //  setInterval(()=>  {
  //     let currentDate = new Date();
  //     this.dateMessage = currentDate.toLocaleTimeString();
  //  }, 1000);

  }

  ngOnInit() {
  }

// Method 2:  This does not work  
  public time_handler() {
    let currentDate = new Date();
    this.dateMessage = currentDate.toLocaleTimeString();
  }
}    

您需要
将此绑定到间隔内的函数

 constructor() {

  setInterval(this.time_handler.bind(this), 1000); 

  //Method 1: This works    
  //  setInterval(()=>  {
  //     let currentDate = new Date();
  //     this.dateMessage = currentDate.toLocaleTimeString();
  //  }, 1000);

  }

否则,handle方法中的
将不会指向类。

由于
设置间隔内的
将指向
窗口
&在
窗口
对象中没有
时间处理程序
函数,因此不起作用的代码


setInterval(console.log(this),3000)
。谢谢我知道这很简单。我建议您在组件损坏时清除间隔