如何避免可观察的Angular中的“ InternalError:过多递归”?

时间:2019-05-31 16:56:39

标签: javascript angular typescript observable

我有一个简单的Angular可观察对象,它应该连续运行,检查每个循环的时间差,然后每秒循环一次。运行它时,我收到“ InternalError:过多的递归”。据此:http://bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code 我使用的是正确的方法。如何解决?

可观察的角度:

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);
  }
}

在另一个组件中的订阅:

// Subscribe to heartbeat over websockets:
MyService.subscribeToHeartbeat(this.handleHeartbeatFailure);

// Handler:
  handleHeartbeatFailure:any = (message) => {
   alert('Websocket is down!")
  }

1 个答案:

答案 0 :(得分:1)

您正在调用该函数,而不是在超时时分配它

setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);

需要成为

setTimeout(() => this.subscribeToHeartbeat(callbackfn), 1000);

或者您可以使用bind

setTimeout(this.subscribeToHeartbeat.bind(this, callbackfn), 1000);