Patiently await the observable to receive an array of data

Although there have been numerous discussions on this topic, I am still struggling to find a solution that works well for me. If you come across one, please do share it with me.

Currently, I am fetching data from an API and converting it into an array of the required datatype:

getData(): Observable<Type[]> {
    return this.http.get<Type[]>("URL)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }

Once I receive the data, I want to use it in my application.

I've tried utilizing while(empty){...}, which appears to be inefficient and incorrect if the array is empty. I also experimented with Promises, but couldn't figure out how to seamlessly integrate them with observables. Additionally, I explored using await/async, but it seems incompatible with observables.

This is how I have implemented the code:

array: Type[] = [];
useJSON(searchString: string) {
    this.configService.getData().subscribe(results => { this.array = results});
    // --operations--
  }

Answer №1

async/away may be the solution you need (though the syntax might be slightly off)

youdMethod() async{
let res=null;

do{
 res=await this.configService.getData().toPromise();
}while(resBasedCondition)
 
}

what you might actually want is to use the repeatIf operator, but unfortunately it's not available. However, you can mimic its behavior using expand as demonstrated here

Answer №2

I'm not entirely certain of your requirements. If there are additional tasks that need to be performed following the initialization of this.array, make sure to include them within the subscription block after the assignment.

arrayData: Type[] = [];
parseJSON(searchTerm: string) {
  this.service.fetchData().subscribe(response => { 
    this.arrayData = response;
    // --additional actions--
  });
}

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 to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...

Encountering a ReferenceError in Angular 4 due to d3 not being defined when importing in a module

I'm looking to incorporate these imports into my angular 4 app.module, rather than adding them directly to my index file. In app.module.ts -> import d3 from "d3"; console.log(d3) // Confirming successful import of D3 import nvd3 from "nvd3"; H ...

Developing a Type-inclusive TypeScript encapsulation for the first level of Array.flat() with generic functionality

I am working on creating a function that constructs an array from the input arguments, allowing for only one type or arrays of that same type. Essentially like (...items)=>items.flat(1), but with type safety and generics. It seems crucial to ensure that ...

Leveraging OAuth 2 with Google

I'm currently working on implementing Google API for user authentication. I have successfully managed to authenticate users, but I am struggling with redirecting users after Sign In and implementing Sign Out functionality. I have been referring to th ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

What is the reason behind receiving the error message "`Foo` only represents a type, but is being treated as a value here" when using `instanceof` in TypeScript?

As the creator of this code interface Foo { abcdef: number; } let x: Foo | string; if (x instanceof Foo) { // ... } Upon running this code, I encountered an error in TypeScript: 'Foo' is recognized only as a type and cannot be used a ...

Out of nowhere, my React App has decided to stop working despite no recent changes

Hi everyone, I recently forked a React app from https://github.com/conedex/frontend. It was working perfectly fine until it suddenly stopped with this error message: ./node_modules/@metamask/utils/node_modules/superstruct/dist/index.mjs 46:43 Module parse ...

Dynamic getter/setter in Typescript allows for the creation of functions

I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass which contains a map of containers: type Container = { get: () => Content s ...

Error encountered in Angular: Trying to assign a value to an empty string array results in the error message "Type (string | undefined)[] is not assignable to

Struggling with an issue in my Angular App - trying to assign a value to an empty array Current environment: node 12.18.4 npm 6.14.8 Here's my typescript.ts code snippet: import { Injectable } from "@angular/core"; import { Product } from ...

`Cannot retrieve object`

this.deleteValue = { LanguageId : '', LanguageName : '', LongName : '', CreatedBy : '', UpdatedBy : '', CreatedDate : '', ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

Creating a TypeScript interface that encompasses both regular arrays and typed arrays

I am interested in utilizing TypeScript for declaring functions with parameters that can accept either a regular JavaScript Array or a Typed Array. However, I am struggling to find an elegant solution for achieving this flexibility. I thought that defining ...

Angular - The parameter type '(error: any) => void' cannot be assigned to the type '() => void'

I encountered an issue with my error handling code in Angular-11: return this.api.post('auth/user/login', data, headers).subscribe( (result: any) => { console.log(result.message); console.log(result.code); if ...

Tips for Using Typescript Instance Fields to Prevent Undefined Values

After creating a few Typescript classes, I encountered an issue where I would get an undefined error when trying to use them after instantiating. I experimented with initializing my fields in the constructor, which resolved the problem, but I don't t ...

Understanding the operator of index type queries and the utility of the extends keyword

While reviewing the documentation on Advanced Types in Typescript, I came across an interesting concept known as the Index Query Operator. The documentation can be found here: https://www.typescriptlang.org/docs/handbook/advanced-types.html. One example pr ...

The callback type in TypeScript is used to define the types

I have encountered this scenario: function createCar(name: string, callback: () => void) function buildEngine(name: string): Engine function createCarWithEngine(carName: string, engineName: string, callback: (param: Engine) => void) { let created ...

HammerJS swipe functionality does not seem to be functioning properly on elements that have the overflow CSS

UPDATE: The code snippet works smoothly when embedded in the question, but encounters issues when edited. This led me to discover that the problem lies with underlying containers that require scrolling... After testing it on my phone, I found that Hammer f ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

How can the radio button's checked property be bound to a boolean attribute of a component in Angular 2?

Is there a way to connect the checked property of a radio button to a boolean variable in a Component class? I would like the radio button in the template to be pre-selected if the boolean flag is true. I attempted to use <input type="radio" [(ngModel) ...

The Angular 8 application is opting for "module" scripts over es5 when loading on IE11

My Angular 8 application is not loading on IE11. After analyzing the index.html, I discovered that it only contains scripts with the attribute type="module" and no es5: <script src="/runtime.js" type="module"></script ...