HTTP requests in Angular
In this video, we’ll look at how to make HTTP requests in an Angular application, using the GET method as an example.
Let’s start by revisiting an important point from the previous lesson: why a new FormControl always has a value of null (FormControl). The reason is that the control’s value can be reset (cleared).
Regarding HTTP requests, Angular provides a built-in HttpClient class, which has methods corresponding to HTTP methods (get(), post(), etc.). It is highly recommended to make HTTP requests in Angular services and then inject these services into your components. This way, components don’t interact with HTTP directly.
HttpClient methods (get(), post(), etc.) don’t return data or a Promise like fetch(). Instead, they return an Observable — an entity from the RxJS library, which we’ll discuss in detail in the next lesson.
app.ts
import {Component, OnInit} from '@angular/core';
import {User, UserService} from './user-service';
import {Observable} from 'rxjs';
import {AsyncPipe} from '@angular/common';
import {ReactiveFormsModule} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.html',
imports: [
ReactiveFormsModule,
AsyncPipe
],
styleUrl: './app.scss'
})
export class App implements OnInit {
protected users: User[] = [];
protected users$!: Observable<User[]>;
constructor(private userService: UserService) {
}
public ngOnInit() {
// this.userService.getUsers().subscribe({
// next: (users) => {
// this.users = users;
// },
// error: () => {}
// });
this.users$ = this.userService.getUsers();
}
}
app.html
<!--<ul>-->
<!-- @for (user of users; track user.id) {-->
<!-- <li>{{user.name}}</li>-->
<!-- }-->
<!--</ul>-->
@let users = users$ | async;
{{users?.length}}
<ul>
@for (user of users; track user.id) {
<li>{{user.name}}</li>
}
</ul>
<ul>
@for (user of users; track user.id) {
<li>{{user.name}}</li>
}
</ul>
user-service.ts
import {inject, Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface User {
id: number,
name: string;
username: string;
email: string;
address: Record<string, string>;
phone: string;
website: string;
company: Record<string, string>;
}
@Injectable({
providedIn: 'root',
})
export class UserService {
protected http = inject(HttpClient);
getUsers(): Observable<User[]> {
return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users');
}
}
0 Comments