Utilizing async/await to pass a variable instead of subscribing to it

In my attempt to utilize the async/await method for a dual API call, I encountered an issue where variables within the second async function were not functioning properly or being rendered by Angular.

const pokemon = this.httpClient
  .get(`https://pokeapi.co/api/v2/pokemon/${pokemon_name}`)
      .subscribe(pokemon => {
        this.image = pokemon["sprites"]["front_default"];
      });

It seems like this problem is related to the life cycle of components in Angular, but I am unsure of how to resolve it

Click here for more details

Answer №1

It may not always be necessary to convert the observable to a promise, especially when dealing with chained requests. Utilizing observables and leveraging RxJS operators designed for such scenarios can offer more flexibility.

In your specific scenario, there are several changes that need to be made:

  1. If the inner request depends on the response from the outer request, consider using the RxJS switchMap operator to map the observable accordingly.

  2. If the outer request returns an array of URLs that need to be fetched individually, you can utilize the RxJS forkJoin function to trigger multiple requests in parallel.

  3. The resulting array of URLs can then be subscribed to using the Angular async pipe in the template.

  4. For displaying an array of images, the *ngFor directive can be used to loop through them.

Controller

import { Component, OnInit } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import { Observable, forkJoin } from "rxjs";
import { switchMap, map } from "rxjs/operators";

@Component({ ... })
export class AppComponent implements OnInit {
  images: Observable<any>;

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.doSometing();
  }

  doSometing() {
    this.images = this.httpClient
      .get("https://pokeapi.co/api/v2/pokemon?limit=151")
      .pipe(
        switchMap((pokemons: any) =>
          forkJoin(
            pokemons.results.map((result: any) =>
              this.httpClient
                .get(result.url)
                .pipe(map((pokemon: any) => pokemon.sprites.front_default))
            )
          )
        )
      );
  }
}

Template

<ng-container *ngIf="(images | async) as urls">
    <h1>Images</h1>
    <img *ngFor="let url of urls" [src]="url"/>
</ng-container>

I've updated your Stackblitz


Note: It's important to note that toPromise() will be deprecated in RxJS 7 and will be removed in RxJS 8.

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 toolbar permanently positioned at the top of the screen

My custom toolbar, along with other components, is present in the app I'm working on. In the app.component, the structure looks something like this: <app-toolbar> </app-toolbar> <main> <a [routerLink]="['/login/en&a ...

Using ng-bootstrap in Angular to filter a JSON object for a typeahead feature

Hello, I am currently working on implementing a typeahead feature in Angular using ng-bootstrap. To achieve this, I have set up a service to fetch JSON data from the server. import { Search } from './search'; export const SEARCH: Search[] = [ ...

How can I set up server-side rendering in Laravel using Angular?

For my single page application built with Angular 5, I decided to integrate it with a Laravel backend. In the Laravel project, I stored all my Angular files within an 'angular' folder. However, I built the actual Angular application outside of th ...

Angular and Bootstrap4: The Perfect Duo for Modals

I need to display a Bootstrap4 modal window in Angular when a specific condition is met in my "bookTour" method without the need for a direct button click. How can I achieve this? Below is the code snippet: html <div class="modal" id="myModal" [ngClass ...

An error occurred in TSX + React: Uncaught TypeError - The property 'setState' cannot be read since it is undefined in Menu.handleClick

Currently, I am utilizing [email protected] along with react and react-dom @15.6.2. Encountering a troublesome issue that I can't seem to debug: Uncaught TypeError: Cannot read property 'setState' of undefined at Menu.handleClick. Thi ...

Dealing with errors when working with an array of Observables in forkJoin: Tips and techniques

In my Angular app, I am fetching an observable stream from an API and I would like to handle errors using forkJoin. import { Observable } from 'rxjs'; import { forkJoin, of, throwError } from 'rxjs'; //Creating an array of observables ...

Guide to updating the content of an input field

As a newcomer hobbyist, I'm attempting to automate my web browsing experience. My goal is to have the browser automatically fill in my username and password, and then click the sign-in button using a combination of JavaScript and Tampermonkey. This me ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

Attempting to locate an element within the DOM using TypeScript

I am completely new to TypeScript. I have been attempting to locate an element using a selector, but no matter what I tried, the findElement() method always returns undefined. Can someone please point out where my mistake might be? Any assistance would b ...

Generating fake data from MongoDB to meet TypeScript requirements in Jest testing

Currently, I am in the process of developing TypeScript interfaces for each model that extends mongoose.Document. import mongoose, { Document } from 'mongoose'; export interface IAccount extends Document { _id: mongoose.Types.ObjectId; name ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Issue with passing object in Angular 2 using ngValue leads to error stating "Property ... is undefined."

When incorporating the following code in my template: <select [(ngModel)]="selectedCompany" class="form-control"> <option *ngFor="let company of companies" [ngValue]="company">{{company.Name}}</option> </select> {{selectedCompa ...

Organize library files into a build directory using yarn workspaces and typescript

When setting up my project, I decided to create a yarn workspace along with typescript. Within this workspace, I have three folders each with their own package.json /api /client /lib The main goal is to facilitate code sharing between the lib folder and b ...

Exploring unnamed objects in JSON responses using RXJS in Angular 5

Currently, the situation is as follows: I am required to dynamically populate a mat-table after receiving a response from an API. Within the JSON response, there are anonymous JSON objects in the "files" array. "files": [ { "title": "dummy", ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

How can I exclude TypeScript files generated from js in WebStorm?

Using the Enable Typescript Compiler option results in a .js file being generated for every .ts and .tsx file by the TypeScript compiler. https://i.sstatic.net/Yr0lR.jpg When performing code completion, WebStorm does not recognize that the files were aut ...

Transform request.post to use async/await syntax

Currently, I have successfully converted many request.get calls to adhere to the new async/await pattern. Now I am curious if there is a similar way to do this for request.post requests as well. Below is a snippet of code that demonstrates what I current ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

What are the different methods to display information in Angular?

list.component.ts import { Component, OnInit } from '@angular/core'; import { StudentAPIService } from 'src/app/services/student-api.service'; import { StudentModel } from 'src/app/model/student'; @Component({ selector: &ap ...

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...