- Angular Tutorial
- Angular - Home
- Angular - Overview
- Angular - Features
- Angular - Advantages & Disadvantages
- Angular Basics
- Angular - Environment setup
- Angular - First Application
- Angular - MVC Architecture
- Angular Components
- Angular - Components
- Angular - Component Lifecycle
- Angular - View Encapsulation
- Angular - Emulated Encapsulation
- Angular - ShadowDom Encapsulation
- Angular - Component Interaction
- Angular - Using @Input Decorator
- Angular - Using @Output Decorator
- Angular - Using Local Variable
- Angular - Using @ViewChild Decorator
- Angular - Using Services
- Angular - Component Styles
- Angular - Nested Components
- Angular - Content projection
- Angular - Single-slot Content Projection
- Angular - Multi-slot Content Projection
- Angular - Conditional Content Projection
- Angular - Dynamic components
- Angular - Using NgComponentOutlet
- Angular - Using ViewContainerRef
- Angular - Elements
- Angular Templates
- Angular - Templates
- Angular - Template statements
- Angular - Template Variables
- Angular - SVG as Templates
- Angular Binding
- Angular - Data Binding
- Angular - Interpolation
- Angular - Event Binding
- Angular - Property Binding
- Angular - Attribute Binding
- Angular - Class Binding
- Angular - Style Binding
- Angular - Two-way Binding
- Angular Directives
- Angular - Directives
- Angular - Attribute Directives
- Angular - Structural Directives
- Angular - Custom Directives
- Angular Pipes
- Angular - Pipes
- Angular - Built-in Pipes
- Angular - Custom Pipes
- Angular Forms
- Angular - Forms
- Angular - Template Driven Forms
- Angular - Reactive Forms
- Angular - Form Validation
- Angular - Dynamic Forms
- Angular Dependency Injection
- Angular - Dependency Injection
- Angular - Injectable Service
- Angular Routing
- Angular - Routing
- Angular - Dynamic Routes
- Angular - Wildcard Routes
- Angular - Nested Routes
- Angular - Navigation
- Angular - Routing in SPA
- Angular - Custom Route Matches
- Angular - Router Reference
- Angular HTTP Client programming
- Angular - Services
- Angular - HTTP Client
- Angular - Express based REST API
- Angular - Request
- Angular - Request Response Workflow
- Angular - Response
- Angular - Express based Upload API
- Angular - GET
- Angular - POST
- Angular - PUT
- Angular - DELETE
- Angular - JSONP
- Angular - CRUD Operations Using HTTP
- Angular Modules
- Angular - Introduction to Modules
- Angular - Root Module
- Angular - Feature Module
- Angular - Sharing Module
- Angular - Routing Module
- Angular - NgModules
- Angular Animation
- Angular - Animations
- Angular Service Workers & PWA
- Angular - Service Workers & PWA
- Angular Testing
- Angular - Testing Overview
- Angular Design Patterns
- Angular - Design Patterns
- Angular - Lazy Loading
- Angular - Singleton Pattern
- Angular - Observer Pattern
- Angular Libraries
- Angular - Libraries
- Angular - Angular Material
- Angular - PrimeNG
- Angular - RxJS
- Angular Advanced
- Angular - Signals
- Angular - Authentication & Authorization
- Angular - Internationalization
- Angular - Standalone Component
- Angular - Accessibility
- Angular - Web Workers
- Angular - Server Side Rendering
- Angular - Ivy Compiler
- Angular - Building with Bazel
- Angular - Backward Compatibility
- Angular - Reactive Programming
- Angular Tools
- Angular - CLI
- Angular Material UI Elements
- Angular - Paginator
- Angular - Datepicker
- Angular - Select Drop-down
- Angular Miscellaneous
- Angular - Third Party Controls
- Angular - Configuration
- Angular - Displaying Data
- Angular - Decorators & Metadata
- Angular - Basic Example
- Angular - Error Handling
- Angular - Testing & Building a Project
- Angular - Lifecycle Hooks
- Angular - User Input
- Angular - What's New?
- Angular Useful Resources
- Angular - Quick Guide
- Angular - Useful Resources
- Angular - Discussion
Angular - HTTP Get Request
The HTTP standard verb GET can be used in HTTP protocol to get (retrieve) a resource (data) from the server. The purpose of theGET method is to request data from the server. The server will check for the specified resource in the server and send it back if it is available.
In Angular, the HttpClient service class provides a get() method to request data from the server using the HTTP GET verb. Let's learn more about this method, including it's signature, parameters, and real-time usage:
Signature of the get() Method
Following is the signature (different from syntax) of the HttpClient get() method −
get<T>(url: string, options?: Object): Observable<T>
Here,
- url − The URL to which the GET request is sent.
- options − represents the options to be send along with the resource URL.
- Observable<T> − The return type, where 'T' represents the expected response type.
To work out the HTTP client-server communication, we need to set up a web application and need to exposes a set of web API. The web API can be requested from the client. Let us create a sample server application, Expense API App, and provide CRUD REST API (mainly GET requests) for expenses.
Create a Server for Expense REST APILet us create a working angular example to get all expense items from the above server application by using the HttpClient service class and get() method −
Angular Sample Application
Step 1: Run the below command to create an angular application −
ng new my-http-app
Enable angular routing and CSS as shown below −
? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? CSS
Step 2: Configure Http client
Let's learn how to configure the HttpClientservice. You need to import the HttpClient in App Config:
provideHttpClient(withInterceptorsFromDi())
app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withInterceptorsFromDi())
]
};
Step 3: Create a new interface, Expense to show the expense items from the server −
interface Expense {
id: Number,
item: String,
amount: Number,
category: String,
location: String,
spendOn: Date
}
export default Expense;
Step 4: Create a new component, ListExpenses to show the expense items from the server −
ng generate component ListExpenses
It will create a new component as shown below −
CREATE src/app/list-expenses/list-expenses.css (0 bytes) CREATE src/app/list-expenses/list-expenses.html (28 bytes) CREATE src/app/list-expenses/list-expenses.spec.ts (602 bytes) CREATE src/app/list-expenses/list-expenses.ts (229 bytes)
Step 5: Include our new component into the App root component view, app.component.html as shown below −
<app-list-expenses></app-list-expenses> <router-outlet></router-outlet>
Step 6: Inject the HttpClient into the ListExpenses component through the constructor as shown below −
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-list-expenses',
imports: [],
templateUrl: './list-expenses.html',
styleUrls: ['./list-expenses.css']
})
export class ListExpenses {
constructor(private http: HttpClient) { }
}
Step 7: Implement the OnInit life cycle hook to request the server for expenses after the initialization of the ListExpenses component −
export class ListExpenses implements OnInit{
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
}
Step 8: Create a local variable, expenses to hold our expenses from the server −
export class ListExpenses implements OnInit{
expenses: Expense[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
}
}
Step 9: Call the get method of this.http (HttpClient instance) object by passing the URL and options to get the expense object from the server. Then, set the expenses into our local variable, expenses −
export class ListExpenses implements OnInit{
expenses: Expense[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get<Expense[]>('http://localhost:8000/api/expense', {
'observe': 'body',
'responseType': 'json'
})
.subscribe( data => {
this.expenses = data as Expense[]
console.log(this.expenses)
})
}
}
Here,
Sets the Expense[] as the type of the object returned by the server. The server will send the array of expense objects in its body in JSON format.
Subscribed to the request (this.http.get) object. Then parsed the subscribed data as an array of expense objects and set it to a local expense variable (this.expenses).
Step 10: The complete code of the ListExpenses is as follows −
list-expenses.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpRequest, HttpResponse, HttpEvent } from '@angular/common/http';
import Expense from '../Expense';
@Component({
selector: 'app-list-expenses',
imports:[],
templateUrl: './list-expenses.html',
styleUrls: ['./list-expenses.css']
})
export class ListExpenses implements OnInit {
expenses: Expense[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get<Expense[]>('http://localhost:8000/api/expense', {
'observe': 'body',
'responseType': 'json'
})
.subscribe( data => {
this.expenses = data as Expense[]
console.log(this.expenses)
})
}
}
Step 11: Next, get the expenses object from the component and render it in our component template page (list-expenses.html) −
list-expenses.html
<div><h3>Expenses</h3></div>
<ul>
@for(expense of expenses; track $index){
<li>
{{expense.item}} @ {{expense.location}} for {{expense.amount}} USD on {{expense.spendOn | date:'shortDate' }}
</li>
}
</ul>
Output
Step 12: Finally, run the application using the below command −
ng serve
Step 13: Now, open your friendly (chrome) browser navigate to http://localhost:4200/ URL, and check the output −
Here, the output shows our expenses as a list of items.
Conclusion
Angular provides an easy way to request the server through the HttpClient object.get() is a specific method used to get resources from the server. We will learn more HTTP methods to target other HTTP verbs in the upcoming chapters.
Multiple Choice Questions (MCQ's):
Here we have mentioned a few MCQs to test your knowledge on the current concept:
Q 1 − What is the primary purpose of an HTTP GET request in Angular?
A − To submit data to a server
B − To retrieve data from a server
Answer : B
Explanation:
The primary purpose of an HTTP GET request is to request data from a specified resource on the server.
Q 2 − Which Angular service is commonly used to make HTTP GET requests?
Answer : C
Explanation:
The HttpClient service is commonly used to make HTTP GET requests in Angular applications.
Q 3 − Which method is used to handle the response of an HTTP GET request in Angular?
Answer : A
Explanation:
The subscribe method is used to handle the response of an HTTP GET request in Angular.