[英]How to avoid “InternalError: too much recursion” in Angular observable?
I've got a simple Angular observable that should run continuously, checking a time difference on each loop, and looping once a second. 我有一个简单的Angular可观察对象,它应该连续运行,检查每个循环的时间差,然后每秒循环一次。 I'm getting "InternalError: too much recursion" when I run it.
运行它时,我收到“ InternalError:过多的递归”。 According to this: http://bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code I'm using the correct method.
据此: http : //bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code我正在使用正确的方法。 How to fix?
怎么修?
The Angular observable: 可观察到的角度:
export class MyService {
private lastHeartBeatTime = null; // Time of the last heartbeat
private heartBeatTimeoutId = null;
private secondsToHeartbeatAlert = 5; // Number of seconds of no heartbeat
constructor() {
this.lastHeartBeatTime = performance.now(); // Initialise local heartbeat variable with current time
}
subscribeToHeartbeat(callbackfn): any {
// Post a value via the observable to cause an alert to be raised:
if((performance.now() - this.lastHeartBeatTime) / 1000 >= this.secondsToHeartbeatAlert) return(true);
// Create a new timeout to call this function again after the specified num of milliseconds (e.g. after 1 second):
// **** PROBLEM HERE: ***
else this.heartBeatTimeoutId = setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
}
}
Subscription within another component: 另一个组件内的订阅:
// Subscribe to heartbeat over websockets:
MyService.subscribeToHeartbeat(this.handleHeartbeatFailure);
// Handler:
handleHeartbeatFailure:any = (message) => {
alert('Websocket is down!")
}
You are calling the function and not assigning it in your timeout 您正在调用该函数,但未在超时中分配它
setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
needs to be 需要是
setTimeout(() => this.subscribeToHeartbeat(callbackfn), 1000);
or you can use bind 或者你可以使用绑定
setTimeout(this.subscribeToHeartbeat.bind(this, callbackfn), 1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.