2017-06-14 98 views
-1

我有一个使用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此方法。这就是为什么我宣称plusstatic,但我无法声明extractAndUpdateMessageList(响应:响应)也是static

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

谢谢

+0

它在哪里使用'setInterval'? –

回答

0

你的subscribe的回调函数内上下文(this)当您使用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为静态,你现在会得到与箭头功能回调内部实例属性。

+0

这实际上是我第一次尝试,但我注意到它并没有计算好像它不存在的条件,无论response.json是否执行内部代码,我真的很困惑... – jiji

+0

@jiji听起来像你的数据有问题。检查'response.json'是否是一个数组,并且你的逻辑是正确的。 – Saravana

+0

我切换到你的技术'((response)=> {',当我做'console.log(response.json())'时,我总是得到'null'但是当我使用'function(response ){'它正确打印数组......我无法弄清楚它! – jiji

0

我想你只需要使用

let that = this; 

,并用“”在地方回调里面。

+0

替换'function(response){'改变类的属性不只是一个局部变量! – jiji