HttpClient
- Angular provides a client HTTP API for Angular applications, the
HttpClient
service class in@angular/common/http
. - Import
HttpClientModule
. - Inject the
HttpClient
service as a dependency.
Create a new file environment.ts
where we will store our server baseUrl
.
export const environment = {
baseUrl: 'http://localhost:3000'
};
Inject the HttpClient
in SportsComponent
and GroceryComponent
to make HTTP requests.
Don’t forget to import HttpClientModule
in imports of standalone component (NgModule
if standalone not used).
export class SportsComponent implements OnInit {
sports: Card[] = [];
private readonly http = inject(HttpClient);
ngOnInit(): void {
this.http
.get<Card[]>(`${environment.baseUrl}/sports`)
.subscribe(sports => this.sports = sports);
}
}
export class GroceryComponent implements OnInit {
grocery: Card[] = [];
private readonly http = inject(HttpClient);
ngOnInit(): void {
this.http
.get<Card[]>(`${environment.baseUrl}/grocery`)
.subscribe(grocery => this.grocery = grocery);
}
}