javascript - 如何避免 Angular observable 中的 "InternalError: too much recursion"?

标签 javascript angular typescript observable

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

Angular 可观察:

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!")
  }

最佳答案

您正在调用该函数,但没有在超时时间内分配它

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

需要

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

或者你可以使用绑定(bind)

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

关于javascript - 如何避免 Angular observable 中的 "InternalError: too much recursion"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56399059/

相关文章:

javascript - jQuery 使用 anchor 的类名将 anchor 的 href 值动态设置为另一个 anchor 的 href 值

javascript - 重写 Backbone 的 URL 函数以从本地存储中获取数据

angularjs - Angular 2 : Inject view/DOM into component constructor

javascript - 使用 NodeJS/ExpressJS 后端服务 Angular 通用应用程序

angular - 如何为 dotnet 核心(web Api)代码更改以及 TypeScript 代码更改启用实时重新加载

angular - 以 Angular 6 从命名空间导出的枚举导致运行时错误

json - 如何使用 typescript (Angular2) 遍历 JSON 对象

javascript - jQuery IIFE,按需插入?

javascript - 多个 DOM appendChild 的速度/效率

angular - 从 ngrx/store 获取单个项目