简体   繁体   中英

Typescript returning Argument of type 'void' is not assignable to parameter of type 'TimerHandler?

I want to update the count of number of message received by use on live server in angular 7 like we have in facebook and linkedin on main page and i have tried the following code:-

the code to fetch message:-

getMessageCount(rid:any)
    {
      return this.http.get<any>(this.apiUrl+'message/'+rid);
    }
on the main page we have the following code run like this :-
export class HomeComponent implements OnInit {
   userAuthenticated=false;
   private tmessage:any;
  constructor(private service:LoginService,private mService:MessagingService) {
    if(this.service.currentUserValue)
    {
      this.userAuthenticated=true;
      const id=this.service.currentUserValue.id;
      window.setInterval(this.getMessages(id),5);

    }
  }
}

upon sending the new message it should be updated without reloading the page ,can anybody tell me what i can do to achieve it ?

You didn't provide getMessages , so I have to guess.

My guess is, getMessages is a void function, doing something, probably updating model/view and not returning anything, while the first parameter of setTimeout should be a function. Therefore, this

      window.setInterval(this.getMessages(id), 5);

should be

      window.setInterval(() => this.getMessages(id), 5);

The problem is setInterval() needs a function as the first argument(also called as a callback function). Then it executes that function after the set amount of time. And also not only run the function once as setTimeout() but regularly after the given interval of time. But you are not giving a function in your code

window.setInterval(this.getMessages(id), 5);

but just giving a value return by the function getMessages(id) .

So the correct way should be

window.setInterval(() => this.getMessages(id), 5);

which now gives a function that can be executed after the given amount of time.

And there is another method where you can call the function by function.call() .

window.setInterval(() => this.getMessages.call(this, id), 5)

call() method calls a function with a given this value and arguments provided individually.

Hope this will help you. (Please correct me if there is anything wrong. Thanks in Advance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM