Guide to performing synchronous HTTP requests in Angular 8 or 9: Sending a request and pausing for a response

A set of three buttons is available:

https://i.sstatic.net/5CRIF.png

By clicking the first button labeled as Request HTTP Data As Promise, you receive its HTTP response in the form of a Promise.

The second button, known as Request HTTP Data As Observable, provides its response as an Observable.

Both these buttons utilize an asynchronous response mechanism to fetch data.

Now, the focus is on the third button named Request HTTP Data and Wait, which is intended to retrieve a synchronous response. This requires waiting for the HTTP service to return the response before moving forward.

To implement this functionality, please refer to the following Stackblitz project link (and utilize the placeholder function getDataSynchronous defined within the HttpService script):

https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts

export class HttpService {
  jsonFile = '../assets/products.json';

  constructor(private http: HttpClient) {}

  getDataAsPromise(): Promise<any> {
    return this.http.get(this.jsonFile)
      .toPromise()
  }

  getDataAsObservable(): Observable<any> {
    return this.http.get(this.jsonFile)
  }

  getDataSynchronous(): any {
    return []
  }

Answer №1

Click for Live Demo An asynchronous function is like a superhero in the coding world, operating seamlessly via the event loop and returning results with an implicit Promise. Despite its advanced functionality, using async functions in your code feels just like working with standard synchronous functions. The powerful await operator allows you to patiently wait for a Promise to fulfill its destiny, but remember, it can only be used within an async function.

fetchDataSync() {
    return  this.http.receiveResponse(this.jsonFile).toPromise()
}

within component

async getDataAndAwait() {
    let fetchedData = await this.fetchDataSync();  
    this.displayResults(fetchedData)  
}

Answer №2

While it may not be the conventional approach in Angular, it is technically possible to accomplish this by utilizing a synchronous XHR request:

getDataSynchronous() {
    var request = new XMLHttpRequest();
    request.open('POST', `${environment.userApiUrl}/logout`, false);  // `false` 
    makes the request synchronous
    request.send({});

    if (request.status === 200) {
        return request.response;
    } else {
        throw new Error('request failed');
    }
}

It's important to note that this method cannot be implemented using Angular HTTP Client and should only be used as a last resort, as synchronous XmlHttpRequest on the main thread is considered to be deprecated in most modern browsers.

Answer №3

Works perfectly for me.

To implement this feature, add the following code snippet to your app.component.ts file:

  ngOnInit(): void
  {
    window.addEventListener('beforeunload', (e) =>
    {
      this.logoutAndWait();
    })
  }

  async logoutAndWait()
  {
    const httpData = await this.userService.logoutSynchronous();
  }

Also, make sure to create a synchronous logout function as shown below:

  logoutSynchronous()
  {
    return this.http.post<string>(`${environment.userApiUrl}/logout`, {}, { withCredentials: true }).toPromise()
  }

Answer №4

One interesting typescript library to explore is ts-sync-request.

Check it out on GitHub: https://github.com/VeritasSoftware/ts-sync-request

You can also find it on NPM: https://www.npmjs.com/package/ts-sync-request

This library allows you to perform synchronous http calls in typescript.

For example:

GET

import { SyncRequestClient } from 'ts-sync-request/dist'
let id = 1;
let url = "http://localhost:59039/api/Movies/" + id;
 
let response = new SyncRequestClient()
                             .addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDc2OTg")
                        .get<Movie>(url);

Answer №5

To achieve this, simply make use of the async and await keywords.

async fetchData() {
  let result = await this.http.get(this.dataFile).toPromise();
  return result;
}

Answer №6

It's impossible to achieve that using JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to incorporate generics into a Typescript method without sacrificing the typing of object keys

Currently, I am working on a method in Typescript that is responsible for extracting allowable property types from an object of a constrained generic type. The scenario involves a type called ParticipantBase which consists of properties like first: string ...

Navigating to Angular component following Jersey and Spring SAML Security Single Sign-On verification

I have a project in progress that utilizes Angular for the front end and Jersey integrated with Spring SAML Security for Single Sign-On (SSO) authentication. My attempt involved initiating the app from Angular (http://localhost:4200), which then makes an ...

Error encountered while loading GitHub Pages resource

Currently, I am facing issues while attempting to host an Angular application with Bootstrap 4 on GitHub Pages using angular-cli-ghpages. The URL I am trying to deploy it at is , but I continuously encounter the following error: Failed to load resource: s ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

Tips for retrieving JSON data from the server through infinite scrolling in Angular 4

Recently, I've been exploring Angular 4 and looking to incorporate infinite scrolling into my project. My goal is to fetch the first 10 items through an HTTP call when the user scrolls down, and then make another HTTP request for the next 10 items to ...

Utilizing query parameters in JavaScript

When querying data from the database using passed parameters, I encountered an issue. For example: http://localhost:3030/people?$skip=0&$limit=25&$sort[name]=0&description[$name]=rajiv I wanted to add an extra parameter without including it in ...

Optimizing your approach to testing deferred always

When creating test cases for code within a jQuery AJAX call's always method or in bluebird promises' finally function, it often involves the following structure: function doStuff() { console.log('stuff done'); } function someFunct ...

Set theme value for the tab group in Angular Material

Trying to change the tab theme in Angular Material by setting it directly seems to be a bit tricky. The example from Angular Material shows how to do it with a toggle button, but when I try to code it directly, it doesn't work. Here's the code sn ...

Ways to add parameters to each external URL using Angular

Seeking thoughts on implementing a feature in Angular to append a parameter to all external URLs or URLs from a specific domain. Let's take as an example. If I were using jQuery, I could achieve this on document ready by doing something like: $(‘ ...

Exploring the integration of Express Session Data with Angular 6

Currently, our setup involves Nginx, Node 8.11, and Angular CLI 6 as we endeavor to transfer the values established in Express back to the frontend of Angular 6. It seems like we have a rather unique arrangement, and I am seeking some guidance on the next ...

SvelteKit Superforms with Zod: An Issue with Checkbox Missing from Form Data

I'm currently in the process of creating a form with SvelteKit Actions, Superforms, Formsnap, and Zod. However, I've encountered an issue with my checkbox not functioning as expected. // schema.ts export const formSchema = z.object({ ... ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...

Transferring an array of data across different screens within an Ionic 2 application

I am a newcomer to Ionic 2 and I am encountering difficulties when it comes to passing data between pages. Within my Home.ts file, there exists a global array containing certain numbers that have been calculated. My intention is to transfer this array to m ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Is it possible to integrate angular-bootstrap-datetimepicker with bootstrap3?

Looking for an accessible date picker solution for my project. The project is built on Bootstrap3, but the angular-bootstrap-datetimepicker has a dependency on Bootstrap4. Can I still integrate angular-bootstrap-datetimepicker with Bootstrap3? ...

What is the best way to implement a <Toast> using blueprintjs?

Struggling without typescript, I find it quite challenging to utilize the Toast feature. This component appears to have a unique appearance compared to the others. Shown below is an example code. How would you convert this to ES6 equivalent? import { But ...

Tips on updating primeng Panel Menu appearance with scss

I'm looking to customize the color of my panel menu to black. Below is the HTML code I am using. <p-panelMenu styleClass="font-bold text-xs m-0 w-11" [model]="items" [multiple]='false'></p-panelMenu> ...

Transfer a value to the ng2 smart table plugin extension

Upon reviewing the document and source code related to pagination implementation in the (advanced-example-server.component.ts), I discovered that the ServerDataSource being used only supported pagination through HTTP GET (_sort, _limit, _page, etc paramete ...

Referring to TypeScript modules

Consider this TypeScript code snippet: module animals { export class Animal { } } module display.animals { export class DisplayAnimal extends animals.Animal { } } The objective here is to create a subclass called DisplayAnimal in the dis ...

Identifying the specific @Input that has changed in ngOnChanges

I am currently utilizing Angular 2. At the moment, I have two @input variables named aa and bb. My objective is: When aa changes, perform a specific action. When bb changes, execute a different action. How can I identify which @Input has changed within ...