Javascript 在setInterval内声明函数不会更新

Javascript 在setInterval内声明函数不会更新,javascript,angular,typescript,setinterval,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.extr

我有一个使用
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;
    };
  });
}
这里的问题是
函数
中定义的所有内容都必须是
静态的
,否则它将是
未定义的
。这就是为什么我将
plus
声明为
static
,但我不能将extractAndUpdateMessageList(response:response)声明为
static

有人能帮我弄清楚如何正确地编写它,而不必将变量声明为
静态

感谢您使用
function(){}
语法进行回调时
subscribe
回调函数中的上下文(
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设置为静态,因为您现在可以通过箭头函数在回调中获得实例属性。

我认为您只需要使用

let that = this;

并在回调中使用“that”

它在哪里使用
setInterval
?这实际上是我第一次尝试的,但我注意到它没有考虑条件,好像它不在那里一样,不管是什么响应。json它确实执行里面的代码,我真的很困惑…@jiji听起来像是数据的问题。检查
response.json
是否是一个数组,您的逻辑是否正确。我切换到了您的技术
((response)=>{
,当我使用
console.log(response.json())
时,括号内的
null
。但是当我使用
函数(response)时{
它正确地打印数组…我搞不懂!!如果我在If打印3之前执行console.log(response.json().length),它仍然会在If中执行代码,即使条件是If(response.json.length==0)!!!jijiji你知道这是不可能的。你是否将你的条件更改为
(response.json().length==0)
?不,关键是要更改类的属性,而不仅仅是局部变量!!