Back to course

Making GET Requests (Fetching Read-Only Data)

The Complete Angular Developer: From Zero to Hero

26. Making GET Requests

GET requests are used to retrieve data from the server. The HttpClient.get() method handles this.

Typing the Response

Always define an interface for the expected API response. This leverages TypeScript's strength and provides type safety for the data we fetch.

typescript interface Post { userId: number; id: number; title: string; body: string; }

// data.service.ts import { HttpClient } from '@angular/common/http';

// ... inside DataService class

getPosts() { // Specify the expected type <Post[]> in the generic parameter return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts'); }

Subscribing in the Component

Since getPosts() returns an Observable, we must subscribe to execute the request and handle the data upon arrival.

typescript // post-list.component.ts import { Post } from './data.service'; import { DataService } from './data.service';

export class PostListComponent implements OnInit { posts: Post[] = [];

constructor(private dataService: DataService) { }

ngOnInit(): void { this.dataService.getPosts().subscribe({ next: (data) => { // Handle successful data retrieval this.posts = data; }, error: (err) => { // Handle errors console.error('Fetch error:', err); }, complete: () => { // Handle completion (optional) console.log('Post fetching completed.'); } }); } }

Note on Unsubscribing: For Observables that complete (like those returned by HttpClient), manual unsubscription is not strictly necessary. However, for long-lived Observables (like timers or router events), unsubscription in ngOnDestroy is mandatory to prevent memory leaks.