How to make synchronous call in Angular?

In Angular, making synchronous HTTP calls is not recommended, as it can lead to a poor user experience by freezing the user interface until the request is complete. The Angular framework and HttpClient are designed to work with asynchronous operations using RxJS and Observables.

However, if you have a specific use case that requires synchronous calls, you can use JavaScript’s XMLHttpRequest (XHR) to make a synchronous HTTP request. Here’s an example of making a synchronous GET request:

  1. First, create a new Angular service:

BASH

ng generate service SyncRequest
  1. Modify the sync-request.service.ts file:

Typsescript

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SyncRequestService {

  constructor() { }

  getData(url: string): any {
    const xhr = new XMLHttpRequest();
    let result;

    xhr.open('GET', url, false); // Set the third parameter to 'false' for synchronous request
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        result = JSON.parse(xhr.responseText);
      }
    };
    xhr.send();

    return result;
  }
}

In this example, we create a getData() function that takes a URL as an argument and makes a synchronous GET request using XMLHttpRequest.

Important: Be aware that making synchronous calls is generally not recommended, as it may cause your application to become unresponsive, negatively affecting the user experience. Asynchronous calls using HttpClient and Observables are the preferred approach in Angular.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts