I have a component in Angular that is responsible for fetching data from the backend.
Below is the code snippet of the component
export class MessagesComponent implements OnInit {
constructor(private _router: Router, private http: HttpClient) {
}
timer: any;
chats: any;
autoresize: boolean = false;
chatId: number;
moment: any = moment;
chatMessages: any;
messageToSend: string;
messageObject: CreateMessageDto = new CreateMessageDto();
ngOnInit(): void {
this.getChatsList();
}
getChatsList(): any {
var reqHeader = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('jwt'),
});
return this.http
.get(environment.baseUrl + '/Chat/GetUserChats', {
headers: reqHeader,
})
.subscribe((data: any) => {
this.chats = data.reverse();
this.getChatId(data[0].id);
});
}
getChatId(chatId: number): any {
this.chatId = chatId;
this.getChatMessages();
}
getChatMessages(): any {
var reqHeader = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('jwt'),
});
return this.http
.post(
environment.baseUrl + '/Messages/GetChatMessages',
JSON.stringify(this.chatId),
{ headers: reqHeader }
)
.subscribe((data: any) => {
this.chatMessages = data;
});
}
createMessage(): any {
this.messageObject.chatId = this.chatId;
var reqHeader = new HttpHeaders({
'Content-Type': 'application/json',
Authorization: 'Bearer ' + localStorage.getItem('jwt'),
});
return this.http
.post(
environment.baseUrl + '/Messages/CreateMessage',
JSON.stringify(this.messageObject),
{ headers: reqHeader }
)
.subscribe((data: any) => {
this.getChatMessages();
});
}
}
I am looking to trigger the getChatsList()
function every 5 seconds after the initialization of the component. How can I achieve this?