UsingThird-party Libraries
You can use third-party libraries like axios, fetch, or rxjs/ajax for making HTTP requests in Angular. For example, you can use the axios library by installing it via npm and then using it in your Angular project.
Example : In this example, we’ll use third party libraries like axios for request
<!-- app.component.html -->
<div class="container" *ngIf="quotes">
<h1>Quotes from Server</h1>
<div class="quote-container" *ngFor="let quote of quotes">
<div class="quote-card">
<p>{{ quote.quote }}</p>
<p>- {{ quote.author }}</p>
</div>
</div>
</div>
/* App.component.css */
.container {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.quote-container {
margin: 20px;
}
.quote-card {
text-align: center;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
width: 200px;
}
// app.component.ts
import { Component, OnInit } from '@angular/core';
import axios from 'axios';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
quotes: { id: number; quote: string; author: string }[] = [];
ngOnInit() {
this.getQuotesFromServer();
}
async getQuotesFromServer() {
try {
const response = await axios.get('https://dummyjson.com/quotes');
this.quotes = response.data.quotes;
} catch (error) {
console.error('Error fetching quotes:', error);
}
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
Make HTTP requests in Angular?
In Angular, making HTTP requests involves communicating with a server to fetch or send data over the internet. It’s like asking for information from a website or sending information to it. Angular provides a built-in module called HttpClientModule, which simplifies the process of making HTTP requests.
With this module, you can easily fetch data from a server, send data to a server, and handle responses. These requests are commonly used to interact with APIs (Application Programming Interfaces) to get or update data in web applications.