Call a function every x seconds in Angular

Call a function every x seconds in Angular

Call a function every x seconds in Angular; Through this tutorial, we will learn how to call a function every x seconds in angular 8, angular 9, angular 10, angular 11, angular 12, angular 13,angular 14, 15, 16 versions.

With the help of this tutorial, we can use a timer() to call API every X (5, 10, 20, 60) seconds in angular apps.

Call a function every x seconds in Angular

Just follow the following steps to call a function every x seconds in angular applications:

  • Step 1 – Create New Angular App
  • Step 2 – Import HttpClientModule
  • Step 3 – Create Service for API
  • Step 4 – Use Service to Component
  • Start 5 – Run Angular App

Step 1 – Create New Angular App

Execute the following command on the command line to create your angular app:

ng new my-new-app

Step 2 – Import HttpClientModule

Then open app.module.ts file and import HttpClientModule to into it; is as follows:

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

  

import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

  

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    HttpClientModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class A

Step 3 – Create Service for API

Execute the following command on command line to create service for http client request; is as follows:

ng g s services/post

Visit to src/app/services/ directory and open post.service.ts. Then add the following code into it:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
  
@Injectable({
  providedIn: 'root'
})
export class PostService {
  private url = 'http://jsonplaceholder.typicode.com/posts';
   
  constructor(private httpClient: HttpClient) { }
  
  getPosts(){
    return this.httpClient.get(this.url);
  }
  
}

Step 4 – Use Service to Component

Then use the above created service in component; so visit src/app/ directory and open app.component.ts file. And then add the following code into it:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { PostService } from './services/post.service';
import { Subscription, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  posts:any;
  subscription !: Subscription;
    
  constructor(private service:PostService) {}
  
  ngOnInit() {
      this.subscription = timer(0, 5000).pipe(
        switchMap(() => this.service.getPosts())
      ).subscribe(result => 
        console.log(result)
      );
  }
  
  ngOnDestroy() {
      this.subscription.unsubscribe();
  }
  
}

Start 5 – Run Angular App

Finally execute the following command on command line to run the Angular app:

ng serve

Recommended Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *