Skip to main content

Working with HTTP Requests

1. Configuring HttpClient

Property Values Description
baseUrl string Base URL for all requests
headers HttpHeaders Default headers to include in all requests
withCredentials boolean Include credentials in cross-origin requests
timeout number Request timeout in milliseconds

Example: Configure HttpClient with base URL and headers

import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
  ],
  providers: [
    {
      provide: HttpClient,
      useFactory: () => {
        const client = new HttpClient();
        client.baseUrl = 'https://api.example.com';
        client.headers = new HttpHeaders({
          'Authorization': 'Bearer token123',
          'Content-Type': 'application/json'
        });
        return client;
      }
    }
  ]
})
export class AppModule { }
Note: The HttpClient in Ionic is built on top of Angular's HttpClient, so configuration options are inherited from Angular.

2. Making GET Requests

Property Value Description
url string The endpoint URL to send the GET request to
method GET HTTP method to use for the request
headers object Optional headers to include in the request
params object Query parameters to append to the URL

Example: Fetching Data with GET

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

constructor(private http: HttpClient) {}

getData() {
  return this.http.get('https://api.example.com/users');
}

Example: GET Request with Query Parameters

getDataWithParams() {
  const params = { page: 1, limit: 10 };
  return this.http.get('https://api.example.com/users', { params });
}
Note: The HttpClient in Ionic uses RxJS Observables, so you must subscribe to the response to trigger the request.

3. Making POST Requests

Property Description Example
url The endpoint to send the POST request to https://api.example.com/users
body Data to be sent in the request body { name: "John", email: "john@example.com" }
headers Additional headers to include in the request { "Content-Type": "application/json" }

Example: Sending a POST Request

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

constructor(private http: HttpClient) {}

sendPostRequest() {
  const url = 'https://api.example.com/users';
  const body = {
    name: "John",
    email: "john@example.com"
  };

  this.http.post(url, body).subscribe(response => {
    console.log("User created:", response);
  });
}
Note: Ensure that the server is configured to accept POST requests at the specified endpoint.

4. Making PUT and DELETE Requests

Method Description Example
PUT Updates an existing resource or creates a new one if it doesn't exist.
import { HttpClient } from '@angular/common/http';

const url = 'https://api.example.com/users/123';
const userData = { name: 'John Doe', email: 'john@example.com' };

this.http.put(url, userData).subscribe(response => {
  console.log('User updated:', response);
});
DELETE Deletes a resource from the server.
import { HttpClient } from '@angular/common/http';

const url = 'https://api.example.com/users/123';

this.http.delete(url).subscribe(response => {
  console.log('User deleted');
});
Note: Ensure proper error handling and status code checks for PUT and DELETE requests.

5. Sending Request Headers

Header Description Example Value
Authorization Used to send credentials for authentication Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type Indicates the media type of the resource application/json
Accept Specifies the media types that are acceptable for the response application/json
User-Agent Contains information about the client's browser or application Ionic App/1.0

Example: Setting Custom Headers in HTTP Request

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

constructor(private http: HttpClient) {}

sendRequestWithHeaders() {
  const headers = {
    'Authorization': 'Bearer token123',
    'Content-Type': 'application/json'
  };

  return this.http.get('https://api.example.com/data', { headers });
}

6. Handling Response Types

Response Type Description Usage Example
json JSON response data For API responses containing structured data const response = await fetch('/api/data');<br>const data = await response.json();
text Plain text response For HTML, XML, or plain content const response = await fetch('/api/html');<br>const html = await response.text();
blob Binary large object response For image or file downloads const response = await fetch('/api/image');<br>const blob = await response.blob();
arrayBuffer Array buffer response For binary data manipulation const response = await fetch('/api/file');<br>const buffer = await response.arrayBuffer();
formData Form data response For form submissions or multipart responses const response = await fetch('/api/upload');<br>const formData = await response.formData();

Example: Fetching JSON Data

const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/users');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const users = await response.json();
    console.log(users);
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
};

Example: Handling Blob Response

const downloadImage = async () => {
  const response = await fetch('https://api.example.com/image.png');
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'image.png';
  link.click();
};

7. Implementing Request Interceptors

Interceptor Type Description Usage
Request Interceptor Modifies outgoing HTTP requests before they are sent Used to add headers, transform data, or log request details
Response Interceptor Modifies incoming HTTP responses before they are processed Used to handle errors, transform response data, or log response details

Example: Adding Authorization Header

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) {
    const authToken = localStorage.getItem('authToken');
    if (authToken) {
      const authReq = req.clone({
        setHeaders: {
          Authorization: `Bearer ${authToken}`
        }
      });
      return next.handle(authReq);
    }
    return next.handle(req);
  }
}

Example: Logging Requests

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Request sent:', req);
    return next.handle(req).do(event => {
      if (event instanceof HttpResponse) {
        console.log('Response received:', event);
      }
    });
  }
}
Note: Interceptors are executed in the order they are provided in the HTTP_INTERCEPTORS array.

8. Handling HTTP Errors

Error Type Code Description Handling Strategy
400 Bad Request 400 The server cannot process the request due to client error. Validate input data and display user-friendly error messages.
401 Unauthorized 401 Authentication is required or has failed. Redirect to login page or refresh token if available.
403 Forbidden 403 Server understands the request but refuses to fulfill it. Inform user they lack permission or redirect to a different resource.
404 Not Found 404 The requested resource could not be found. Display a custom 404 page or redirect to home.
500 Internal Server Error 500 Unexpected condition that prevented the server from fulfilling the request. Log error details and show generic error message to user.
503 Service Unavailable 503 The server is temporarily unable to handle the request. Implement retry logic or show maintenance message.

Example: Error Handling in Ionic HTTP Client

import { HttpClient } from '@angular/common/http';
import { catchError, retry } from 'rxjs/operators';

constructor(private http: HttpClient) {}

getData() {
  return this.http.get('https://api.example.com/data').pipe(
    retry(1),
    catchError((error) => {
      if (error.status === 401) {
        // Handle unauthorized access
        console.error('Unauthorized: Please log in.');
      } else if (error.status === 404) {
        // Handle not found
        console.error('Resource not found.');
      } else if (error.status === 500) {
        // Handle internal server error
        console.error('Server error occurred.');
      }
      return throwError(error);
    })
  );
}
Note: Use retry operator for transient errors like network timeouts or 503s.
Warning: Never expose raw error messages to users in production. Always sanitize and provide user-friendly feedback.

9. Using Loading Indicators with HTTP

Example: Displaying a loading indicator during HTTP request

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

@Component({
  selector: 'app-example',
  template: &#x27;<ion-content>
  <div *ngIf="loading">Loading...</div>
  <div *ngIf="!loading">{{ data }}</div>
</ion-content>&#x27;
})
export class ExampleComponent {
  data: any = null;
  loading = false;

  constructor(private http: HttpClient) {}

  fetchData() {
    this.loading = true;
    this.http.get(&#x27;https://api.example.com/data&#x27;).subscribe({
      next: (res) => {
        this.data = res;
        this.loading = false;
      },
      error: () => {
        this.loading = false;
      }
    });
  }
}
Property Description Default
loading Boolean flag to control visibility of loading indicator false
Note: Use loading state to show/hide UI elements like spinners or progress bars during HTTP requests.

10. Implementing Request Timeout

Property Description Default Value Notes
timeout Timeout in milliseconds for HTTP requests 5000 Used to prevent hanging requests

Example: Setting Request Timeout

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

const timeout = 10000; // 10 seconds
this.http.get('https://api.example.com/data', { timeout }).subscribe({
  next: (response) => console.log(response),
  error: (error) => {
    if (error.name === 'TimeoutError') {
      console.error('Request timed out');
    }
  }
});

Was this article helpful?