如何在angular2中创建计时器 [英] How to create timer in angular2

查看:95
本文介绍了如何在angular2中创建计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要Angular 2中的一个计时器,它在一个时间间隔后打勾并执行一些任务(可能会调用一些函数)。

I need a timer in Angular 2, which tick after a time interval and do some task (may be call some functions).

如何使用Angular执行此操作2?

How to do this with Angular 2?

推荐答案

除了之前的所有答案,我都会使用RxJS Observables

In Addition to all the previous answers, I would do it using RxJS Observables

请查看可观察。计时器

这是一个示例代码,将在2秒后开始,然后每秒滴答:

Here is a sample code, will start after 2 seconds and then ticks every second:

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'my-app',
    template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
  ticks =0;
  ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=>this.ticks = t);
  }
}

这是一个工作 plunker

更新
如果要调用在AppComponent类上声明的函数,可以执行以下操作之一:

Update If you want to call a function declared on the AppComponent class, you can do one of the following:

**假设要调用的函数已命名 func

** Assuming the function you want to call is named func,

ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(this.func);
}

上述方法的问题在于,如果你在func中调用'this' ,它将引用订阅者对象而不是AppComponent对象,这可能不是您想要的。

The problem with the above approach is that if you call 'this' inside func, it will refer to the subscriber object instead of the AppComponent object which is probably not what you want.

但是,在下面的方法中,您创建一个lambda表达式并调用其中的函数 func 。这样,对func的调用仍然在AppComponent的范围内。在我看来,这是最好的方法。

However, in the below approach, you create a lambda expression and call the function func inside it. This way, the call to func is still inside the scope of AppComponent. This is the best way to do it in my opinion.

ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=> {
        this.func(t);
    });
}

检查此plunker 用于工作代码。

这篇关于如何在angular2中创建计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆