angular examples authentication http-calls web-development http-interceptors error-handling get-requests post-requests
0 likes

Making HTTP Calls in Angular: A Comprehensive Guide with Examples


Certainly! Let's provide examples for some of the key concepts mentioned in the article "Making HTTP Calls in Angular: A Comprehensive Guide."

1. Making a GET Request:

To make a GET request in Angular, you can use the HttpClient module. Here's an example of fetching data from a hypothetical JSON API:

Copy Code
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getData() {
  const apiUrl = 'https://api.example.com/data';
  return this.http.get(apiUrl);
}

2. Handling GET Request Response:

You can handle the response using Observables. For instance, in a component:

Copy Code
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
  data: any;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(response => {
      this.data = response;
    });
  }
}

3. Making a POST Request:

To make a POST request with data, you can use the HttpClient module like this:

Copy Code
import { HttpClient, HttpHeaders } from '@angular/common/http';

constructor(private http: HttpClient) {}

postData(data: any) {
  const apiUrl = 'https://api.example.com/data';
  const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  return this.http.post(apiUrl, data, { headers });
}

4. Handling Errors:

Handle errors using the .catch() operator in Observables:

Copy Code
import { catchError } from 'rxjs/operators';

getData() {
  const apiUrl = 'https://api.example.com/data';
  return this.http.get(apiUrl).pipe(
    catchError(error => {
      console.error('Error:', error);
      throw error;
    })
  );
}

5. Using HTTP Interceptors:

Create an HTTP interceptor to add headers to outgoing requests:

Copy Code
import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
} from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Add authentication token to headers if available
    const authToken = 'your-auth-token';
    const authReq = req.clone({
      setHeaders: { Authorization: `Bearer ${authToken}` },
    });
    return next.handle(authReq);
  }
}

Don't forget to provide the interceptor in your app module.

These examples cover some of the fundamental concepts discussed in the article. For a comprehensive understanding and more in-depth examples, please refer to the detailed explanations and code samples provided in each section of the article.

0 comments