Angular 16 http service example; Through this tutorial, i am going to show you how to create httpclient and http services in Angular 16 apps.
Angular 16 HttpClient & Http Services Example
Follow the below given steps to create httpclient and http services in Angular 16 apps; as follows:
- Step 1: Create New App
- Step 2: Import HttpClientModule
- Step 3: Create Service for API
- Step 4: Use Service to Component
- Step 5: Updated View File
- Step 6: Run Angular App
Step 1: Create New App
Run the following command on command prompt to create new angular app; as follows:
ng new my-new-app
Step 2: Import HttpClientModule
Go to src/app directory and open app.module.ts file and import modules into it; 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 AppModule { }
Step 3: Create Service for API
Run the following command on the command prompt to create service; as follows:
ng g s services/post
Go to src/app/services/ directory and oen post.service.ts file; and 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
Go to the src/app/ directory and open app.component.ts; and add the following code into it; as follows:
import { Component, OnInit } from '@angular/core'; import { PostService } from './services/post.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { posts:any; constructor(private service:PostService) {} ngOnInit() { this.service.getPosts() .subscribe(response => { this.posts = response; }); } }
Step 5: Updated View File
Go to the src/app/ directory and open app.component.html. And then add the following code; as follows:
<h1>Angular 13 HttpClient for Sending Http Request Example - laratutorials.com</h1> <ul class="list-group"> <li *ngFor="let post of posts" class="list-group-item"> {{ post.title }} </li> </ul>
Step 6: Run Angular App
Run the following command on the command prompt to start angular app; as follows:
ng serve