Javascript 如何在angular2中创建计时器
我需要一个在Angular 2中的计时器,它在一个时间间隔后滴答作响并执行一些任务(可能是调用一些函数)Javascript 如何在angular2中创建计时器,javascript,angular,Javascript,Angular,我需要一个在Angular 2中的计时器,它在一个时间间隔后滴答作响并执行一些任务(可能是调用一些函数) 如何使用Angular 2实现这一点?除了前面的所有答案之外,我还将使用RxJS观测值实现这一点 请查收 下面是一个示例代码,将在2秒后开始,然后每秒都会打勾: import {Component} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'my-app',
如何使用Angular 2实现这一点?除了前面的所有答案之外,我还将使用RxJS观测值实现这一点 请查收 下面是一个示例代码,将在2秒后开始,然后每秒都会打勾:
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);
}
}
这是一份工作报告
更新
如果要调用AppComponent类上声明的函数,可以执行以下操作之一:
**假设要调用的函数名为func
上述方法的问题在于,如果在func中调用“this”,它将引用subscriber对象而不是AppComponent对象,而AppComponent对象可能不是您想要的对象
但是,在下面的方法中,创建一个lambda表达式,并在其中调用函数func。这样,对func的调用仍然在AppComponent的作用域内。我认为这是最好的方法
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
检查工作代码。另一种解决方案是使用TimerObservable 是可观测的一个子类
import {Component, OnInit, OnDestroy} from '@angular/core';
import {Subscription} from "rxjs";
import {TimerObservable} from "rxjs/observable/TimerObservable";
@Component({
selector: 'app-component',
template: '{{tick}}',
})
export class Component implements OnInit, OnDestroy {
private tick: string;
private subscription: Subscription;
constructor() {
}
ngOnInit() {
let timer = TimerObservable.create(2000, 1000);
this.subscription = timer.subscribe(t => {
this.tick = t;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
注意:别忘了取消订阅。我遇到了一个问题,我必须使用计时器,但我必须在同一时间、同一屏幕上以两个组件显示它们。我在服务中创建了timerObservable。我订阅了这两个组件中的计时器,发生了什么?它不会同步,因为新订阅总是创建自己的流 我想说的是,如果您计划在多个位置使用一个计时器,请始终放置
.publishReplay(1).refCount()
在观察者的末尾,因为它每次都会从中发布相同的流
例如:
this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => {
return this.calculateTime(startDate);
}).publishReplay(1).refCount();
发现了一个npm包,它使RxJS作为一项服务变得简单
您可以“订阅”现有计时器,这样,如果您在同一组件中多次使用它,就不会创建大量计时器。您只需使用setInterval实用程序并使用arrow函数作为回调函数,以便
此
将指向组件实例
例如:
this.interval = setInterval( () => {
// call your functions like
this.getList();
this.updateInfo();
});
在Ngondestory生命周期挂钩中,清除间隔
ngOnDestroy(){
clearInterval(this.interval);
}
如果希望在ngOnInit上运行方法,可以执行以下操作: 从RXJS导入这两个库:
import {Observable} from 'rxjs/Rx';
import {Subscription} from "rxjs";
然后声明计时器和专用订阅,例如:
timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc
private subscription: Subscription;
最后一个但并非最不重要的运行方法是在计时器停止时运行
ngOnInit() {
this.subscription = this.timer.subscribe(ticks=> {
this.populatecombobox(); //example calling a method that populates a combobox
this.subscription.unsubscribe(); //you need to unsubscribe or it will run infinite times
});
}
仅此而已,Angular 5通过rxjs 6.2.2和Angular 6.1.7,我得到了:
Observable.timer不是一个函数
错误。通过将可观察计时器
替换为计时器
,解决了这一问题:
import { timer, Subscription } from 'rxjs';
private myTimerSub: Subscription;
ngOnInit(){
const ti = timer(2000,1000);
this.myTimerSub = ti.subscribe(t => {
console.log("Tick");
});
}
ngOnDestroy() {
this.myTimerSub.unsubscribe();
}
设置定时器,并在一定时间后自动呼叫服务
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}
getNotifications() {
setInterval(() => {this.getNewNotifications();
}, 60000); // 60000 milliseconds interval
}
getNewNotifications() {
this.notifyService.getNewNotifications().subscribe(
data => { // call back },
error => { },
);
}
包含足够的代码以允许其他人重现问题。有关这方面的帮助,请阅读如何创建一个最小、完整且可验证的示例。如果可以创建一个可以链接到的问题的实例(例如,on或),那么就这样做,但也要在问题本身中包含代码。不是每个人都可以访问外部站点,而且链接可能会随着时间的推移而中断。这实际上是一个非常有用的问题。观察值对于学习和使用很重要。即使用户没有代码,这个问题也会对其他人有帮助。这个评论属于同一个范围,但前两个人都没有帮助,只是对这个问题发表了评论。。。显然,人们现在又在使用setTimeout了。setTimeout真的很老派——请在下面签出新的TimerObservable设置此选项。_timer=setInterval(()=>this.getWidgetData(),10000);并确保调用clearInterval(此计时器);在销毁时,我应该能够将函数传递给'timer.subscribe(t=>this.ticks=t);`每个tick中调用哪个?@matrixwebtech是的,'t=>this.ticks=t'是一个lambda表达式,与'function(t){this.ticks=t}'完全相同,我尝试使用timer.subscribe(function name(){console.log(“hhhhhhh”);但我如何调用一个单独声明为ngOnInit(){let timer=Observable.timer(20001000);timer.subscribe(function(){this.fun();});}fun(){console.log(“hhhhhh”)}@matrixwebtech的函数请检查我的更新答案以获取示例。@不要在引擎盖下翻页,
计时器
似乎使用了setInterval()
。但是,您可以传递animationFrame
调度程序(它使用requestAnimationFrame()
)来使用它,而不是默认的async
调度程序。您所需要做的就是Observable.timer(*,*,Scheduler.animationFrame)
,给定import{Scheduler}自'rxjs'
。尽管在timer
上它似乎不起作用。它似乎仍然使用setInterVal()
。但是,在其他类型的可观察对象上,例如observable.range(01000,Scheduler.animationFrame)
,肯定会使用requestAnimationFrame
。就性能而言,我现在不能肯定地回答您。退订部分是关键。您如何退订?组件反初始化期间调用?@Notflip ngondestory时:this.subscription.unsubscripte()代码>取消订阅。您如何能够在不引用上述内容的情况下使用此.subscription?如何暂停并重新启动它?这不会添加其他答案中未解释的任何内容,或者会添加其他答案中未解释的内容?您可以共享您的实现吗?要执行取消订阅,您必须有一个订阅变量,如上面的@alexis poo。请参阅:。我是基于你的回答,在这方面没有写出来。我爱这个家伙,他总是更新帖子到最新版本。。。每次和AngularJS和AngularJS斗争太多。谢谢你,伙计!
import { timer, Subscription } from 'rxjs';
private myTimerSub: Subscription;
ngOnInit(){
const ti = timer(2000,1000);
this.myTimerSub = ti.subscribe(t => {
console.log("Tick");
});
}
ngOnDestroy() {
this.myTimerSub.unsubscribe();
}
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}
getNotifications() {
setInterval(() => {this.getNewNotifications();
}, 60000); // 60000 milliseconds interval
}
getNewNotifications() {
this.notifyService.getNewNotifications().subscribe(
data => { // call back },
error => { },
);
}