Welcome folks today in this blog post we will be making a http
request to json placeholder api to render data
inside the browser using typescript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new angular
project using the below command as shown below
ng new angularproject
cd angularproject
And after that you need to go to app.module.ts
file and include the HttpClientModule
as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 { } |
And then we need to make a posts
service where we will be making the http
get request to the jsonplaceholder
api as shown below
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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); } } |
And now we need to import this service inside the app.component.ts
file as shown below
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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; }); } } |
And now we need to make the app.component.html
file and inside we need to loop through the posts
using the ngFor
directive as shown below
app.component.html
1 2 3 4 5 6 7 |
<ul class="list-group"> <li *ngFor="let post of posts" class="list-group-item"> {{ post.title }} </li> </ul> |