在Angular中使用setInterval调用函数时无法读取undefined的属性

时间:2019-08-11 14:49:03

标签: javascript angular typescript ecmascript-6

在调用函数时没有任何问题,但是在setInterval中调用它时,不断地每秒调用它会给我一个错误:无法读取服务上未定义的属性!

 constructor(private route: ActivatedRoute,private 
 conversationService:ConversationService) {
 }


 ngOnInit() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(
 function()
 { 
   this.conversationService.
   getTheConversation(this.receiver,this.sender).subscribe(
     data=>this.result=data)
   },1000);
 } 

错误: 错误TypeError:无法读取未定义的属性'getTheConversation'

2 个答案:

答案 0 :(得分:2)

函数setInterval引用了另一个对象

正确的方法是

const newThis = this;
setInterval(
 function()
 { 
   newThis.conversationService.
   getTheConversation(newThis.receiver,newThis.sender).subscribe(
     data=>newThis.result=data)
   },1000);

关注该链接以了解更多其他方法https://stackoverflow.com/a/7890978/11914056

答案 1 :(得分:1)

尝试

 ngOnInit() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(()=>
 { 
   this.conversationService.
   getTheConversation(this.receiver,this.sender).subscribe(
     data=>this.result=data)
   },1000);
 } 

使用胖箭头 =>来维护this范围。声明新的function时,它会创建自己的this