Waiting for an Angular Observable to complete its process

I have recently developed a small Angular application that retrieves data from a REST API using observables. However, I am facing an issue with their asynchronous nature.

let tempArray: boolean[] = [];
for (let i = 0; i < 3; i++) {
    this._myservice.checkData(data[i]).subscribe(
        result => {
            tempArray.push(result);
            console.log('Before');
            console.log(tempArray);
        },
            error => console.log(error),
    );
}
console.log('After');
console.log(tempArray);

The problem arises when the result data does not end up in the correct array after the subscription, as shown in the screenshot below. Is there a way to resolve this issue without having to relocate all the code inside the subscription block?

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

Answer №1

If you want to combine multiple observable streams and wait for all of them to complete before taking action, you can utilize the forkJoin operator. This is similar to using Promise.all, but specifically designed for observables.

import { forkJoin } from 'rxjs/observable/forkJoin';

forkJoin(
  this._myservice.checkData(data[0]),
  this._myservice.checkData(data[1]),
  this._myservice.checkData(data[2])
).subscribe(result => {
  // result[0] represents the first result
  // result[1] represents the second result
  // result[2] represents the third result
});

Answer №2

The best approach is to utilize the async/await functionality, which essentially encapsulates all the code within a subscription without explicitly writing it:

let boolArray: boolean[] = [];
const promises = Promise<bool>[];
for (let index = 0; index < 3; index++) {
    promises.push(this._myservice.checkData(data[index]).toPromise());
}

// Create a promise that combines the previous ones and await it:

try {
    boolArray = await Promise.all(promises);
} catch (error) {
    console.log(error)
}

console.log('After');
console.log(boolArray);

It's worth noting that async/await operates with promises instead of observables, but converting one into the other is straightforward - Just ensure that you import toPromise from RxJS.

For further insights on async/await, you can refer to this resource https://basarat.gitbooks.io/typescript/docs/async-await.html

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

The Ionic Menu fails to display when the modal is chosen

Upon logging into the app, users encounter a modal that prompts them to enter data before proceeding to the logged-in page. This page is supposed to display a menu, which I have enabled by calling this.menu.enable on the home page. However, despite enablin ...

Is there a way to modify my port to 4900 using npm?

Is there a way to change my port to 4900 using npm, since the command ng s --port 4900 is not working for me? Here is the error message I receive: PS G:\PROJECTS\PetroHSE> ng s --port 4900 ng : The term 'ng' is not recognized as ...

Is it beneficial to consolidate masterdata calls into a single call?

Our application is built using REST with an Angular 2 client. We frequently make calls to master data APIs such as country and agreement during login, totaling around 6-7 calls. From a performance standpoint, would it be beneficial to consolidate these c ...

Is it possible to verify if an object matches a type without explicitly setting it as that type?

In order to illustrate my point, I believe the most effective method would be to provide a code snippet: type ObjectType = { [property: string]: any } const exampleObject: ObjectType = { key1: 1, key2: 'sample' } type ExampleType = typeof ...

Concealing Angular Features Using a Button

Currently, I am experimenting with Angular and attempting to create a button that disappears when clicked. Despite trying methods like [hidden], (click)="showHide = !showHide", and several others, nothing seems to be working as expected. This is the curre ...

What is the solution for resolving the error message "Property '' does not exist on type 'typeof import'"?

Hi everyone, I'm a new Angular developer who is working on implementing authentication. I recently added the auth0-angular package to my project and now I'm encountering an error when creating a WebAuth() instance in my code editor (VS Code). Th ...

File or directory does not exist: ENOENT error encountered when attempting to access 'distrowserindex.html'

Upon executing ng deploy --preview, an error is encountered: Error: ENOENT: no such file or directory, open 'dist\index.html' at Object.openSync (fs.js:457:3) at readFileSync (fs.js:359:35) Despite attempting various online tutorial ...

What is the best way to hand off a component to a helper function?

I am trying to create a helper function in TypeScript that takes a component as an argument and returns an array of objects, each containing a component node... // helpers.ts import { LINKS } from '../constants'; // error on the next line: Cannot ...

Deploying Nodejs code with Express leads to an error message stating that the class module is not found

Upon completion of compiling TypeScript files, I receive JavaScript files structured as follows: main directory public api controllers data-controller.js app.js package.json ... The code in app.json is ...

Accessing information from an Angular Elements Web Component using vanilla JavaScript

I am in the process of creating several WebComponents that I plan to utilize across various libraries and frameworks, with a primary focus on plain vanilla JavaScript. My current consideration is to implement Angular Elements for this purpose, and I have a ...

The Angular project I am hosting on GitHub Pages seems to be having trouble locating its files, leading to a

After successfully building an Angular project using the ng build command, I ran into an issue when uploading it to a GitHub repository and creating its GitHub Page. Despite working perfectly locally, none of the bundle files could be found when accessing ...

Unusual class title following npm packaging

Currently, I am working on developing a Vue 3 library with TypeScript. We are using Rollup for bundling the library. Everything works as expected within the library itself. However, after packing and installing it in another application, we noticed that th ...

Access the uploaded file as a stream through Express

I'm currently working on an API that includes a function to upload files to another website, acting as a proxy for the file upload process through the API. The destination website requires specific steps to be followed (such as sending the destinatio ...

Troubleshooting issues with sorting and pagination in Angular Material table functionality

I am experiencing an issue with sorting and pagination using an Angular material table. The data is being fetched from a store as an observable and successfully displayed in the table. Even though the column names for sorting match the column definitions, ...

The GUI does not reflect changes observed in Angular

Even though I have subscribed in names.component to a subject that triggers when the subject is changed, my GUI does not react to the "lang" change. Why is this happening? This component resides in fields.module.ts and the CacheService is provided by the ...

The ng update fails when trying to upgrade the CLI from version 7 to version 8

Attempting to upgrade the Angular CLI version from v7 to v8 through the ng upgrade command results in failure. Even manual attempts to upgrade the CLI first are unsuccessful. ng update @angular/cli The global Angular CLI version (8.0.1) is higher tha ...

Can you explain the significance of ?. in Angular 5?

While I understand that product.id == 1 ? stuff : not stuff simplifies to choosing "stuff" if the id is 1 and "not stuff" otherwise, I am unsure about the meaning of the following code: product?.id.name ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Filter the angular accordion by passing a simple array value into the input

I am looking to filter my array of accordion items based on the value of the question matching the input I provide. I have tried using the filter method for this. this.accordionItems = [ { "topic":"polizze", " ...

When attempting to initiate a new Angular project, the error below is being encountered

Seeking assistance with this error. I am attempting to create a new angular app using ng new app-name, but encountering the following issue. Being new to Angular, I'm unsure about the cause of this error. CREATE angular-app/e2e/src/app.e2e-spec.ts (3 ...