我的setInterval时间似乎不起作用

时间:2019-03-22 14:18:28

标签: javascript angular

我是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();
  }
}    

2 个答案:

答案 0 :(得分:1)

您需要将此bind插入间隔内的函数。

 constructor() {

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

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

  }

handle方法中的其他this不会指向该类。

答案 1 :(得分:0)

由于this中的setInterval将指向window且在window对象中没有time_handler函数,因此该代码不起作用

setInterval(console.log(this), 3000)

这就是为什么您的代码不起作用

但是您注释的代码有效,因为您正在使用箭头功能,而在箭头功能中,这是指周围的范围。

当您使用bind返回一个新函数并被明确绑定时