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)
?不,关键是要更改类的属性,而不仅仅是局部变量!!