0
0
Angularframework~5 mins

GET requests in Angular

Choose your learning style9 modes available
Introduction

GET requests let your app ask a server for data. It is like looking up information in a book.

When you want to show a list of items from a server, like products or users.
When you need to load details about something, like a user profile or article.
When you want to refresh data without changing anything on the server.
When you want to fetch configuration or settings from a server.
When you want to get data for charts or reports.
Syntax
Angular
this.http.get<YourDataType>('https://api.example.com/data').subscribe(response => {
  // use the response data here
});

Use HttpClient service from Angular to make GET requests.

The subscribe method listens for the server response.

Examples
Fetches an array of names as strings and logs them.
Angular
this.http.get<string[]>('https://api.example.com/names').subscribe(names => {
  console.log(names);
});
Fetches a single item object and logs its title.
Angular
this.http.get<{id: number, title: string}>('https://api.example.com/item/1').subscribe(item => {
  console.log(item.title);
});
Fetches data with query parameters for pagination.
Angular
this.http.get('https://api.example.com/data', { params: { page: '1', limit: '10' } }).subscribe(data => {
  console.log(data);
});
Sample Program

This Angular component fetches a list of users from a public API using a GET request. It then shows the users' names in a list.

Angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-get-example',
  template: `
    <h2>Users List</h2>
    <ul>
      <li *ngFor="let user of users">{{ user.name }}</li>
    </ul>
  `
})
export class GetExampleComponent {
  users: { id: number; name: string }[] = [];

  constructor(private http: HttpClient) {
    this.loadUsers();
  }

  loadUsers() {
    this.http.get<{ id: number; name: string }[]>('https://jsonplaceholder.typicode.com/users')
      .subscribe(data => {
        this.users = data;
      });
  }
}
OutputSuccess
Important Notes

Always import HttpClientModule in your app module to use HttpClient.

GET requests should not change data on the server; use POST, PUT, or DELETE for that.

Handle errors by adding catchError or error callback in subscribe.

Summary

GET requests ask the server to send data without changing it.

Use Angular's HttpClient and subscribe to get and use data.

GET is good for loading lists, details, or refreshing data.