在setInterval中声明函数不会更新

时间:2017-06-14 16:35:54

标签: javascript angular typescript setinterval

我有这种使用setInterval

的方法
public getMoreMessages(route: string) {
  this.http.get(this.url + route + "?page=" + MessageService.plus)
           .subscribe(function(response) {
    if (response.json.length === 0) {
      MessageService.plus++;
      this.extractAndUpdateMessageList(response);
      return;
    };
  });
}

这里的问题是function中定义的所有内容都必须是static,否则它将是undefined。这就是我将plus声明为static的原因,但我也无法将{strong> extractAndUpdateMessageList(响应:响应)声明为static

有人可以帮我弄清楚如何正确编写它而不必将我的变量声明为static吗?

谢谢

2 个答案:

答案 0 :(得分:0)

当您使用this语法进行回调时,subscribe的回调函数内的上下文(function() {})。使用arrow functions捕获正确的this

this.http.get(this.url + route + "?page=" + MessageService.plus)
  .subscribe((response) => { // Notice arrow function here
    if (response.json.length === 0) {
      MessageService.plus++;
      this.extractAndUpdateMessageList(response);
      return;
    };
  });

您不必将MessageService.plus设置为静态,因为您现在将使用箭头函数在回调中获取实例属性。

答案 1 :(得分:0)

我认为你只需要使用

let that = this;

并使用"那"在回调中的位置。