Angular asynchronous calls nested within each other

I'm facing an issue with a function that calls a service to retrieve data via an API. The goal is to make another call with an updated offset if the result equals 50 after the first call. However, despite my efforts, it seems like it doesn't enter the arrow function as expected:

result: any[] = []

   async getData(v) {
      await this.gs.getMaxGifs(v, this.offset).subscribe((response: any) => {
      this.result.push(...response.data);
      this.offset += 50;
      if (this.result.length % 50 == 0) {
          console.log('DENTRO')
          async () => {
            await this.gs.getMaxGifs(v, this.offset).subscribe((response: any) => {
              console.log('DENTRO22222')
            })
            this.result.push(...response.data);
            this.offset += 50;
          }
      }
      console.log(this.result.length)
    });
  }

https://i.sstatic.net/RziOM.png

Once I get this part working, my plan is to replace the if statement with a while loop. But when I tried to add it now, it resulted in an infinite loop.

Answer №1

It successfully worked for sirss,

When looking at the code snippet, we can see that the asynchronous function getData is being called with a parameter v. Inside this function, there is a call to this.gs.getMaxGifs which returns an Observable. Upon subscribing to this Observable, it pushes the response data into a result array and increments the offset by 50. If the length of the result array is divisible by 50, it logs 'DENTRO' to the console and recursively calls getData with the same parameter v.

Answer №2

result: any[] = []

 processInformation(v) {
  this.gs.fetchGifsData(v, 
   this.offset).subscribe((response: any) => {
  this.result.push(...response.data);
  this.offset += 50;
  if (this.result.length % 50 == 0) {
      console.log('INSIDE')
      
        this.gs.fetchGifsData(v, this.offset).subscribe((response: any) => {
          console.log('INSIDE AGAIN')

        
        this.result.push(...response.data);
        this.offset += 50;
      }
  }
  console.log(this.result.length)
});
}

Alternatively, to achieve the same result recursively, you can use the following approach:

    result: any[] = []

 processInformation(v) {
  this.gs.fetchGifsData(v, 
   this.offset).subscribe((response: any) => {
  this.result.push(...response.data);
  this.offset += 50;
  if (this.result.length % 50 == 0) {
      this.processInformation(v)
  }
  console.log(this.result.length)
});
}

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

How can I prevent the creation of undefined fields in Typescript when initializing a new object?

I'm working with the data structure Player: type Player = { id: Scalars['ID']; name: Scalars["String"]; age: Scalars["Int"]; description?: Maybe<Scalars["String"]>; __typename?: "Player" ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Laravel 5.4 integrates with Angular4: Implementing Passport token requests

Trying to make a Token request from API using: Signin(email: string, password: string): void { let data: Object = { client_id: 2, client_secret: 'vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms', grant_type: 'password&a ...

React with Typescript prop is functioning well, despite displaying an error

After creating a component and passing props to styled components, everything seems to be working fine. However, I keep encountering this error on the first prop. Component type WelcomeProps = { image: String, color: String } const StyledWelcom ...

The module '@angular/cdk/testing' cannot be located

Currently, I am experimenting with the createKeyboardEvent function provided by @angular/cdk/testing to simulate keyboard events: const ENTER_EVENT = createKeyboardEvent('keydown', ENTER, inputNativeElement); Despite installing @angular/cdk usi ...

Which is better: Utilizing ASP.NET Core or ASP.NET Core MVC in tandem with Angular for the

Currently in the planning stages of developing a website or web application using .NET Core for the backend and Angular for the frontend. One aspect that is proving to be confusing is whether to use ASP.NET Core or ASP.NET Core MVC on the backend. I'm ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Unable to utilize a service from a module that is shared when leveraging ClientsModule.registerAsync() functionality

In my current project setup, I have developed a shared config module that incorporates multiple config modules. Each of these config modules exports its own service, and the shared module, in turn, exports all the imported modules. At the moment, my applic ...

Getting environment variables on the client side in Next.js: A step-by-step guide

How can I retrieve an environment variable in my Next.js application and pass the data into datadogRum.init? // _app.tsx import React from "react"; import { useEffect } from "react"; import type { AppProps } from "next/app"; ...

Ported an Angular application to Android with the help of Cordova. The APK successfully launches on the emulator, however, when tested on a physical device, only a blank

Struggling to convert my angular app with Cordova to an android app. The APK file works on the emulator, but when installed on a real device, it only shows a white blank screen, never loading. Seeking assistance as I am new to Cordova and Android developme ...

Error: We were unable to recognize the syntax in /service-details/1139#overview for Angular 5

I have been working on implementing simple routing in Angular. Everything seems to be functioning correctly, however, I encountered an error when attempting client-side routing using nav tabs to navigate within the same page. Here is a snippet of my code: ...

Styling in Angular 4 based on conditions

I am currently using this html code and it is working perfectly: <button class="button-style standard-button button-blue" (click)="onOkClick()" [ngClass]="{'disabled': !hasUnsavedNotes()}" [disabled]="!hasUnsavedNotes()"> Save and close & ...

Encountering a Geolocation API issue during the troubleshooting of an Angular application on

Currently, I'm in the process of developing an angular application that utilizes the GeoLocation API to retrieve user location. To achieve this, I make use of the navigator.geolocation.getCurrentPosition() function. Surprisingly, everything works perf ...

Encountering the "DevToolsActivePort file does not exist" error when executing Angular e2e tests via GitHub Actions

Currently delving into the world of GitHub actions, I am in the process of executing Angular e2e tests within a continuous integration workflow. Utilizing the basic project structure generated by the Angular CLI, I have primarily focused on adjusting the ...

What is the proper way to specify the type for the iterable response of Promise.all()?

It's common knowledge that Promise.all will return settled promises in the same order of the requested iterable. I'm currently grappling with how to correctly define types for individual settled resolves. I am utilizing Axios for handling asynch ...

Incorporate a visual element into an Angular Library Component Template using an image asset

Currently, I am working with Angular 10 and aiming to develop a component library that includes images and stylesheets. My main goal is to be able to access these images from the component templates defined in the HTML template. Although I have limited ex ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

Updating a URL parameter in Angular using programmatic methods

If I have a dynamic component that shows information about different characters in a story. Once a character is chosen, specific details will be displayed within the same component. The objective is to include both the story id and character id in the URL ...

Why is TypeScript unable to locate the identifier 'Express'?

Embarking on an express application using TypeScript. Displayed below is the code in app.ts: import express = require("express"); let app: Express = express(); I've successfully installed Express by using npm install --save express @types/expres ...