Steps for converting an observable http request into a promise request

Here is a link to my service file: This is the TypeScript file for my components: And these are the response models:

I am currently facing difficulties with displaying asynchronously fetched data in my component's TypeScript file using an Observable-based service. I have learned that converting the service to Promise-based structure could help, but I am struggling with implementing the responseModel provided by Observables in a Promise-based setup. Any guidance on this issue would be greatly appreciated.

Also, here are some outputs from my project:

Answer №1

If you're working with RxJS version 7.8.0, my suggestion would be to utilize the lastValueFrom method

For example:

import { HttpClient } from '@angular/common/http';
import { lastValueFrom, take } from 'rxjs';

class YourService {

  constructor(
    private readonly httpClient: HttpClient,
  ) {}

  async yourFunction(): Promise<YourTypeOrInterface> {
    const request$ = this.httpClient.get(yourUrl).pipe(take(1));

    return await lastValueFrom<YourTypeOrInterface>(request$);
  }

}

.toPromise() is no longer recommended and will be phased out completely in RxJS 8.

Answer №2

Observables come equipped with a method called .toPromise()

const response = await this.currencyService.getAllByDate(...).toPromise()

MODIFY Ensure that your call stack remains asynchronous throughout

async ngOnInit(): Promise<void> {
    await this.getAllByDate();
    ...
}

async getAllByDate() {
    let date;
    if (this.selectedDate == null) {
        date = new Date(Date.now()).setHours(3,0,0,0);
    } else {
        date = new Date(this.selectedDate).setHours(3,0,0,0);
    }

    const response = await this.currencyService.getAllByDate(new Date(date)).toPromise();

    if (response && isArray(response.data)) {
        this.currencies = response.data;
        this.currencies.push(newCurrency);
    }
}

REVISE As the usage of toPromise() is being phased out, in future versions you would need to create your own promises

const promise = new Promise((resolve, reject) => {
    this.currencyService.getAllByDate(...)
        .pipe(take(1))
        .subscribe({ complete: resolve, error: reject })
});

const response = await promise;

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

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .pane ...

Styles in print CSS are not effective in an Angular project

Currently, I am working on an Angular project where I need to generate a printable document using CSS. The challenge I am facing is ensuring that the date and title in the header do not print automatically when the document spans multiple pages. Additional ...

What is the approach to constructing an observable that triggers numerous observables depending on the preceding outcome?

One of my endpoints returns { ids: [1, 2, 3, 45] }, while the other endpoint provides values for a given id like { id: 3, value: 30, active: true }. I am currently attempting to create an observable that will call the first endpoint and then, for each id r ...

What is the best way to incorporate the async pipe into my codebase when working with GraphQL queries?

I am currently working on an Angular project where I utilize GraphQL to fetch data in my component. In the HTML code, I display an image of the result. However, I encountered an error in the console that said: ERROR TypeError: Cannot read property 'im ...

Obtaining the Froala text editor's instance in React: A step-by-step guide

Is there a way to access the Froala editor instance within my React components? I've noticed that the official Froala documentation doesn't provide instructions for achieving this in React, only in jQuery. ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Using Angular2 to assign the response from an http.get request to a class object

I am a beginner in Angular and I have a JSON file that holds the configuration URL for my application. Path: app/config/development.json { "apiUrl": "http://staging.domain.com:9000/", "debugging": true } Below is the content of my config.service.t ...

Out of the blue, Angular has inexplicably ceased to function in development, production, and local environments, despite successfully

TypeError: n is not iterable TypeError: n is not iterable I am currently working on an Angular and Node.js project hosted on Heroku. Everything was running smoothly until recently when I encountered an error after successfully building Angular. Upon loadi ...

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

Achieving success with a straightforward ng2 webpack starter pack

Webpack-starter has been a great tool to work with, but I need something simpler for my mind. That's how I first started using webpack with react and redux. My goal is to gradually build up from the basics. -simple -dist index.html -s ...

Extracting an array from an HTTP response in Angular/Typescript using the map operator or retrieving a specific element

Q1: How can I extract an array of objects from a http response using map in Angular? Q2: Is there a way to retrieve a specific object from a http response by utilizing map in Angular? Below are the example URL, sample data, CurrencyAPIResponse, and Curre ...

Encountering an error when attempting to store a value in an array of custom types: "Unable to assign properties to undefined (setting 'id')"

My model looks like this: export class SelectedApplicationFeatures { id: number; } In my TypeScript file, I imported the model as shown below: import { SelectedApplicationFeatures } from "src/app/models/selectedApplicationFeatures.model"; selec ...

Angular's ng toolkit universal experiencing loading issues and tools are malfunctioning

I encountered the following issue npm run build: prod commands are not functioning correctly ERROR: Cannot read property 'length' of undefined ERROR: If you think that this error shouldn't occur, please report it here: https://githu ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

Using MSAL for authentication in combination with NGRX for state management

I am currently using MSAL login, which automatically redirects to the Microsoft login page. However, when I set the cache location to 'none' instead of 'localStorage', it is not redirecting. I prefer not to store the token in local sto ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Mouse event listener includes timeout function that updates a global variable

I'm currently working on a function that gets activated by a mouse click, but there's a 10-second cooldown period using setTimeout() before it can be triggered again. However, after the timeout, my variable doesn't get set to the correct boo ...