Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png

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: https://i.sstatic.net/rIRjt.png

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

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Opting out of notifications using Angular's NGXS

I'm new to NGXS in Angular and have recently learned that you don't need to manually unsubscribe when using the async pipe. However, I am currently subscribing to both query parameters and dispatched actions. Do I still need to manually unsubscri ...

When using Array.find() in TypeScript, the Subscribe function does not get called

I am currently diving into Typescript and web development, but I've encountered a peculiar issue when subscribing to an event that's leaving me stumped. In my service, I'm using a BehaviorSubject to store a carId, and on a page where there&a ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

What are the steps to access a query parameter within an API route.js file using the latest App routing strategy?

Here is the goal I am aiming for: Utilize Next.js with App router. Establish a backend route /api/prompt?search=[search_text] Retrieve and interpret the search query parameter in my route.ts file. Based on the search parameter, send back data to the front ...

Angular Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

Is it possible to automatically switch to a different route in a Next.js server component after a certain period of time?

Is it possible to achieve a similar function in an async server component: displaying the ui, waiting 3 seconds, and then redirecting to another route? In a client component, you can accomplish this using: useEffect(() => { function delay(ms: number) ...

Issues retrieving data using Ionic 4 native HTTP plugin result in returning an empty

Currently, I am working on an Ionic 4 project where I am attempting to retrieve a JSON array from a URL using the native HTTP for Ionic. However, when I attempt to fetch the data array from the URL in JSON format, I am met with an empty page. The JSON dat ...

Submitting a form via NextJS to an internal API

After reading through the Next.JS documentation, I came across an interesting point. Note: Instead of using fetch() to call an API route in getStaticProps, it's recommended to directly import the logic from within your API route and make necessary cod ...

Issue with comparing strings in Typescript

This particular issue is causing my Angular application to malfunction. To illustrate, the const I've defined serves as a means of testing certain values within a function. Although there are workarounds for this problem, I find it perplexing and woul ...

Tips for incorporating nested generics in Typescript

Currently, I am developing a straightforward activity execution framework that allows developers to define activities which can be executed within a workflow. To enhance type safety and boost developer productivity by utilizing type hints, I aim to incorp ...

What sets apart HttpClient.post() from creating a new HttpRequest('POST') in Angular?

I've recently started learning angular, and I've noticed that there are two different ways to make a POST request: constructor(private httpClient: HttpClient) { httpClient.post(url, data, options); } constructor(private httpClient: HttpClie ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

Utilize async/await to send images using node mailer

How can I correctly access mailOptions in the triggerExample.ts file? mail.ts: export const sendNewMail = async (html: string, emails: string[]) => { let smtpTransport = nodemailer.createTransport({ service: "Gmail", auth: { u ...

Adjusting the interface of a third-party TypeScript library

I am currently working on modifying a third-party interface. I'm curious about why this particular code is successful: import { LoadableComponentMethods as OldLoadableComponentMethods } from '@loadable/component'; declare module "load ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Avoid using the <app-componentName> tag when displaying content in an Angular application

Is there a way to exclude the <app-componentName> tag from being generated in Angular HTML output? Let me illustrate what I mean using an example: Imagine I have a chat-box with a message component structured like this: <div class="chatbox&q ...

Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format: console.log(req.body) { productid:[1, 2, 3] qty: [3, 5, 6] } I'm trying to implement a for loop to use these values in SQL queries. However, I e ...

Sending Angular signal from child component to parent component

While working in Angular, I have been utilizing event emitters to transmit data from a child component to a parent component. This allows the parent component to update shared data based on notifications from the child. Now with Signal being introduced i ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...