Automatically execute a function every 5 seconds in Angular application

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?

Answer №1

Implement the interval function from rxjs to make a call every second.

  import { interval } from 'rxjs';

  ngOnInit(): void {
      interval(5000).subscribe(() => {
          this.getChatsList();
      });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Is it possible to host an Angular application on one port and a legacy application on another within a virtual machine?

I'm struggling to articulate this question properly, so please bear with me (or offer guidance) if I'm not doing it correctly. Here's the situation: In my Angular 4 app, the files are located on my host operating system (Ubuntu 16.04) and ...

JavaScript code that filters and combines two arrays based on the matching of two fields or columns

Looking for a solution with childcare schools - I have two sets of data that I need to match based on specific columns: Attendance by Department: [date, department, attended] 0: (3) ["09-30-2019", "00_Infants", 22] 1: (3) ["09-30-2019", "01_Ones" ...

The width of the Bootstrap tooltip changes when hovered over

Currently, I am facing a peculiar issue with my angular web-application. Within the application, there is a matrix displaying data. When I hover over the data in this matrix, some basic information about the object pops up. Strangely, every time I hover ov ...

Automatic Slideshow

I am trying to implement autoplay in my slider, but I am having trouble figuring out how to do it. The slider itself is working fine, but I know that I need to use an interval for the autoplay feature. If anyone could provide some assistance on how to ac ...

Trigger an AJAX request by clicking on a specific div element

My goal is to trigger an AJAX call when a user clicks on a location marker in a Google map integration. The function info_window_content, available at this link: http://jsfiddle.net/6xw2y/, is responsible for creating the necessary div elements within the ...

Tips for synchronizing the indexes of two arrays using a common value in JavaScript

Is there a way to sort one array to match the order of another array with identical content, based on a shared property? For instance: let firstArray = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // always in this order let secondArray = [{id: 456, . ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

Error in Typescript for callback function: The type 'Function' does not match any signature

I am encountering an error stating that Type 'Function' does not match the signature for the filter function below. This is because the filter function expects a specific type. How can I define my callback function to align with what the filter f ...

What is the process behind Twitter's ability to quickly show my profile?

Scenario I was intrigued by the different loading times of Twitter's profile page based on how it is accessed: Clicking the profile link in the menu results in a 4-second load time with DOM and latest tweets loade ...

Creating a draggable element in JavaScript using React

I've been attempting to create a draggable div element, but I'm encountering some perplexing behavior. The code I'm using is directly from w3schools and it functions correctly for them, however, in my implementation, the div always shifts to ...

What is the most effective method for attaching a jQuery click event to every anchor tag within each row of a table?

Displayed here is a grid (basic html table) showcasing users with the option to delete a specific user by clicking on the delete link. My typical approach involves: <% foreach (var user in Model.Users) {%> <tr > <td align="right"><% ...

What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet. index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined" Sample Code: <div class="formCustomerName"> <label>Name:</label> ...

Troubleshooting CORS Problems with jQuery and Spring Boot

Recently, I have encountered an issue with my front-end pages that are developed using jQuery 3.2.1 and running by npm. Here is a snippet of how it is set up: "start": "http-server -a localhost -p 8000 -P http://localhost:8080 -c-1 --cors ./app" When mak ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

Initial part before entering the line of input

Is there a way to add a prefix to input blocks similar to how Python does it? E:\Users\foobar\Downloads\KahootTest1>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", ...

In React/Next.js, it seems that pressing the useState button twice is required in order for an event to trigger

When working with react/nextjs, I encountered an issue with a click event where I'm trying to use setState to modify an array. Strangely, the modification only takes effect after two clicks of the button. Here is the initial state array: const [array ...

Using jQuery, you can enclose a string of text with HTML tags easily

This specific content within the span is being dynamically created by PHP. However, I am uncertain how to efficiently target the text string in order to begin using jQuery. <!-- input: --> <span class="price">RM1,088.00 Annually + RM10.00 Se ...

How to dynamically add list items to a jQuery Mobile list using Ajax requests

Included in my index.html is a list view: <section id="dashboard" data-role="page" data-transition="slide"> <header data-role="header"> <h1>Trips</h1> <a href="#addTrip" id="createNewTrip" d ...