我有这种使用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
吗?
谢谢
答案 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;
并使用"那"在回调中的位置。