Git Tutorial

Angular Http Calls

This tutorial demonstrates how to use provideHttpClient in an Angular standalone app for back end calls.

1. Update App Bootstrap with provideHttpClient

Update your main.ts file to include provideHttpClient.

src/main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter, Route } from '@angular/router';

import { AppComponent } from './app/app.component';
import { HomeComponent } from './app/home/home.component';
import { AboutComponent } from './app/about/about.component';
import { ContactComponent } from './app/contact/contact.component';
import { AuthGuard } from './app/auth.guard';

const routes: Route[] = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent, canActivate: [AuthGuard] },
];

bootstrapApplication(AppComponent, {
providers: [provideHttpClient(), provideRouter(routes)],
}).catch((err) => console.error(err));

2. Create a Data Service

Create a service to handle HTTP requests.

src/app/data.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class DataService {
private apiUrl = 'https://jsonplaceholder.typicode.com/users'; // Mock API URL

constructor(private http: HttpClient) {}

// Fetch user data from the API
getUsers(): Observable<any[]> {
return this.http.get<any[]>(this.apiUrl);
}
}

This service handles API calls using the HttpClient injected through Angular’s DI system.

3. Update Contact Component

Use the DataService in the ContactComponent to fetch and display data.

src/app/contact/contact.component.ts:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { CommonModule } from '@angular/common';

@Component({
selector: 'app-contact',
standalone: true,
imports: [CommonModule],
template: `
<h1>Contact Us</h1>
<p *ngIf="authService.isLoggedIn(); else notLoggedIn">
Here are the user details fetched from the API:
<ul>
<li *ngFor="let user of users">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</p>
<ng-template #notLoggedIn>
<p>Please log in to see contact details.</p>
</ng-template>
`,
styles: [`h1 { color: orange; }`],
})
export class ContactComponent implements OnInit {
users: any[] = [];

constructor(private dataService: DataService, public authService: AuthService) {}

ngOnInit(): void {
if (this.authService.isLoggedIn()) {
this.dataService.getUsers().subscribe({
next: (data) => (this.users = data),
error: (err) => console.error('Error fetching users:', err),
});
}
}
}

Benefits of provideHttpClient

  1. Tree-shakable: provideHttpClient ensures unused HTTP-related features are excluded during build.
  2. Standalone-first: Aligns with Angular’s move towards standalone components.
  3. Simpler Setup: No need for HttpClientModule imports; just configure it during app bootstrap.

3 thoughts on “Angular Http Calls”

  1. Pingback: What Is Angular - Tech Mentor

  2. Hello just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Chrome.

    I’m not sure if this is a fotmat issue or something to do with browser compatibility butt I
    thought I’d post to let you know. The layout look great though!
    Hope you get tthe issue fixed soon. Kudos https://evolution.org.ua/

  3. Hello just wanted to give you a quick heads up. The text in your
    post seem to be running off the screen in Chrome. I’m not sure if this is a format isse oor something to do with
    browser compatibility but I thought I’d post to let you know.
    The layout look great though! Hope you get the issue fixed soon. Kudos https://evolution.org.ua/

Leave a Comment

Your email address will not be published. Required fields are marked *