3

When calling a function without any problem,but when call it in setInterval so keep calling it each second it gives me the error: cannot read property of undefined on the service!

 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);
 } 

error: ERROR TypeError: Cannot read property 'getTheConversation' of undefined

logeshpalani31
  • 1,416
  • 12
  • 33
Amine Maalfi
  • 145
  • 9
  • why not use rxjs Timer? some like `timer(0,1000).pipe(switchMap(()=>{return this.conversationService.getTheConversation(this.receiver,this.sender)})).subscribe(data=>this.result=data)` – Eliseo Aug 11 '19 at 18:41

2 Answers2

4

Try

 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);
 } 

use fat arrow => to maintain this scope. When you declare a new function , it creates it's own this.

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
2

The function setInterval is referring to a different this object,

The correct way to do this would be,

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

Follow the link for more other ways of doing it https://stackoverflow.com/a/7890978/11914056

Chetan Naik
  • 613
  • 3
  • 12