In this tutorial we’ll learn to fetch data from a REST API in Angular 17. We’ll be using HTTP client and standalone components.
Let’s get started by creating a new Angular 17 project using the following command:
ng new angular17http
Navigate inside your project and run the following command to create a component:
ng g c posts
Open the src/app/app.component.ts
file then import and add PostsComponent to the imports array as follows:
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { PostsComponent } from './posts/posts.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, PostsComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'angular17http';
}
Next, open the src/app/app.component.html
and call the PostsComponent
as follows:
<app-posts></app-posts>
Next, go to the src/app/posts/posts.component.ts
file and update it as follows:
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, inject } from '@angular/core';
@Component({
selector: 'app-posts',
standalone: true,
imports: [HttpClientModule],
templateUrl: './posts.component.html',
styleUrl: './posts.component.css'
})
export class PostsComponent { httpClient = inject(HttpClient);
public data: Array<any> = []; ngOnInit() {
this.httpClient.get('https://jsonplaceholder.typicode.com/posts')
.subscribe({
next: (data: any) => {
console.log(data);
this.data = data;
}, error: (err) => console.log(err)
});
}
}
We import HttpClientModule
via the imports
array of the component and we inject the HttpClient
service then we call the get method of HttpClient
to send a GET request to the API endpoint and we subscribe to the returned Observable. Then we simply display the data in the browser’s console and assign it to the data
array.
Next, open the src/app/posts/posts.component.html
file and display the data using the @for
directive:
@for (post of data; track post.id){
<h1> {{ post.title }}</h1>
<p> {{ post.body }} </p>
}
Go to the terminal and serve your Angular 17 project using this command:
ng serve
Go to your web browser and navigate to http://localhost:4200/
. You should see the fetched posts in the console.