简体   繁体   中英

Call angular service inside setInterval

I want to send data to backend (py) and want to display loading icon until finish the process. also I set status variable in the backend to "working" or "Done" to check the running. My problem is how to check the status every 3 second from setInterval in js.

runPy() {
this.request.run(this.values).then(id=>{
  this.id = id
  this.checkloading(this.id)})
}
checkloading(id) {
  this.interval = setInterval(function()
  {
    this.request.status(id).then(status=>{
      this.status = status
      if(status == "Working"){this.loading = true}
      else{this.loading = false
        clearInterval(this.interval)
      }
    });
  }, 3000);

}

Also, I realize that the problem is: id undefined, when I set this.id=id in runPy() and alert it, it alert: undefined! Any ideas?

Change the function(){} to an arrow function to have the value of this still pointing to the class.

checkloading(id) {
  this.interval = setInterval(() => {
    // now this will work and the this keyword will be pointing to the class
    this.request.status(id).then(status=>{
      this.status = status
      if(status == "Working"){this.loading = true}
      else{this.loading = false
        clearInterval(this.interval)
      }
    });
  }, 3000);

A good read for you: https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM