Asynchronous problem when using Firebase calls within an Angular ForEach loop

Here's the code snippet I'm working with:

getTotalBookListCost(bookList:string[]):number
  {
    let cost=0;
    bookList.forEach(el=>{
      this.store.doc("Books/"+el).get().subscribe(data=>{
        let temp=<Book>data.data();
        cost+=temp.cost;
      },error=>this.toastr.error(error.message));
    });
    return cost;
  }

The issue is that the value returned is always 0, most likely because the return statement is being executed before the forEach loop completes the Firebase calls. How can we make sure the function returns only after the loop has finished executing?

Answer №1

Absolutely, the function will provide the data prior to Firebase returning it. One potential solution is to utilize the combineLatest operator in the following manner:

getTotalBookListCost(bookList:string[]):Observable<number>
{
  let cost=0;
  return 
  combineLatest(bookList.map(el=>this.store.doc("Books/"+el).get())
  .pipe(
      map(result=> {
        const bookCosts = result.map(data => data.data().cost);
        return bookCosts.reduce(function(a, b) { return a + b; }, 0);
      })
  );
}

It's important to note that your function will now output an Observable instead of just a number.

Edit: as Andrei pointed out correctly, the function previously returned a Subscription instead of an Observable. I have corrected this error, so please remember to subscribe to the Observable.

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

Blending ASP.NET Core 2.0 Razor with Angular 4 for a Dynamic Web Experience

I am currently running an application on ASP.NET Core 2.0 with the Razor Engine (.cshtml) and I am interested in integrating Angular 4 to improve data binding from AJAX calls, moving away from traditional jQuery methods. What are the necessary steps I need ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

angular-ouath2-oidc fails to redirect following user authorization

I'm working on implementing angular-oauth2-oicd for obtaining users' permission to access their basecamp3 accounts. The application is able to successfully load the access request, but I'm facing an issue where upon clicking 'grant acce ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

The Angular 13 interceptor is not capturing a 403 error as expected

When it comes to running a .NET 6 API, the Angular 13 application is encountering an issue with intercepting a 403 error. Strangely enough, the 401 error is being handled properly. The problem lies in the fact that the 403 error does not trigger the (err: ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

Creating a dynamic variable reference for ngModel in Angular 2 and above allows for flexible data binding

I am faced with a situation where I need to populate a table's headers based on the JSON data {id, name}. The ngModel name I have used in the component is this.id which needs to be mapped for custom filtering accordingly. For example, list=[{id:age ...

Unknown Angular component identified

I'm currently working on an application with the following structure: app |-- author |-- |-- posts |-- |-- |-- posts.component.html |-- |-- author.component.html |-- |-- components |-- |-- tag |-- |-- |-- tag.component.ts |-- home |-- |-- home.comp ...

Transferring an array of Json objects to Firestore

My Json object Array is meticulously organized and quite extensive, following this format: { "object1":[ { "data1":19.77, "data2":-0.953125, "data3":-0.265625, "id&qu ...

How can I resolve the problem of transferring retrieved data to a POST form?

When it comes to the form, its purpose is to send data fetched from another API along with an additional note. The fetched data was successfully received, as I confirmed by logging it to the console. It seems that the form is able to send both the fetche ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Leveraging Angular CLI in conjunction with the newest AspNetCore Angular 4 Single Page Application template

I'm currently experimenting with using Angular CLI alongside the latest JavaScriptServices AspNetCore Angular Spa template. In the past, I would simply copy and paste a .angular-cli.json file into my project's root directory, change "root" to "C ...

Stuck in a possible freeze while verifying the session cookie within firebase authentication

When attempting to verify the sessionCookie using the code snippet below, the process freezes without displaying the log(sessionCookieString). What could be causing this freeze? node.js export const sign = functions_address.https.onCall( (data,conext) =& ...

Oops! Encounter an issue while trying to deploy VueJS App on Firebase Hosting

I recently developed a Vue application and integrated firebase tools to deploy it on Firebase hosting. Initially, everything worked fine when I ran npm run build and firebase deploy. However, upon making changes and attempting to use commands like npm run ...

Contrasting input: [] with the @Input() directive

Recently, I've begun exploring the world of child and parent component communication in Angular 4. In my research, I stumbled upon older videos that utilize the input: [] syntax instead of the now more prevalent @Input() syntax. Is there any distincti ...

Angular 2 component: Harnessing the power of boolean inputs

I am currently working on creating a reusable component for my application that may display a control button at times and hide it at others. My ideal scenario would involve utilizing the presence or absence of an attribute to determine whether the control ...