How can you perform HTTP requests in Angular? Provide an example.

Answer

In Angular, you can perform HTTP requests using the built-in HttpClient module. It provides methods to send HTTP requests such as GET, POST, PUT, DELETE, etc. Here's an example of making an HTTP GET request to retrieve data from a server:

 

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

@Component({
selector: 'app-data',
template: `
<h1>Data List</h1>
<ul>
<li *ngFor="let item of data">{{ item.name }}</li>
</ul>
`
})
export class DataComponent implements OnInit {
data: any[];

constructor(private http: HttpClient) { }

ngOnInit() {
this.http.get<any[]>('https://api.example.com/data')
.subscribe(
response => {
this.data = response;
},
error => {
console.error('Error:', error);
}
);
}
}

 

In this example, we have a DataComponent that makes an HTTP GET request to retrieve data from the https://api.example.com/data endpoint. The HttpClient service is injected into the component's constructor, allowing us to use its methods.

Inside the ngOnInit lifecycle hook, we use the get() method of HttpClient to send the GET request. The get() method returns an Observable, which we can subscribe to using the subscribe() method. In the subscription, we handle the response data and assign it to the data property of the component.

If the request is successful, the response will contain the retrieved data, which we assign to the data property. If an error occurs, the error callback will be executed, and we can handle the error accordingly.

In the template, we use *ngFor to iterate over the data array and display each item's name property.

This is a basic example of performing an HTTP GET request in Angular using the HttpClient module. Similar approaches can be used for other HTTP methods like POST, PUT, DELETE, etc., provided by the HttpClient module.

All angular Questions

Ask your interview questions on angular

Write Your comment or Questions if you want the answers on angular from angular Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---