The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> {
    this.subRecords = await this.afs.collection<Records>('records')
        .valueChanges()
        .subscribe((data: Records[]) => {
            console.log('log before data saved');
            this.records = data as Records[];
        });
    console.log('log before return');
    return await this.records;
}

My issue lies in the order of execution of this code. The log before data saved appears after the return statement, causing a delay in saving the data. I am seeking a solution to ensure that the function returns the records promptly and stores them in my this.records array.

Answer №1

If you're looking to retrieve data from a single query, it's best not to utilize valueChanges(), as it does not return a promise. valueChanges is typically used when you want to establish a listener for data that may change over time.

In your situation, consider using get() instead, which provides a promise that resolves with the results of the query, as demonstrated here.

await this.afs.collection<Records>('records').ref.get()

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

What is the method for ensuring TypeScript automatically detects the existence of a property when an object is statically defined?

In my software, I have an interface that serves as a base for other types. To simplify things for this discussion, let's focus on one specific aspect. This interface includes an optional method called getColor. I am creating an object that implements ...

Blend various observables in real-time using RxJS

I'm currently dealing with a recursive issue where I am unsure when my Observable will complete within a recursive function. The scenario is this - I have a function that scrapes a website with pagination and returns an Observable that continuously p ...

Exploring Angular 2 Beta 8: An Introduction to @Query Usage

My attempt to utilize @Query to fetch data regarding an element in my template has not been successful. I made an effort using the following approach: Referenced here. Here is a snippet of my code, import {Component, Query, QueryList, ElementRef} from &a ...

Page access will be protected by authentication

Looking for advice from those experienced with Angular2/ Ionic on how to restrict access to pages only when authenticated. Although there are a few pages that don't require authentication, the majority need it. Is there a way to automatically push the ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

"Encountered a runtime error while trying to execute the doubleClick() function using Pro

Encountering the following issue: "WebDriverError: Unable to convert: Error 404: Not found" while running a test with protractor: browser.actions().doubleClick(elem).perform(); or browser.actions().click(elem).click(elem).perform(); Uncertain of t ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

eslint warning: the use of '$localize' is flagged as an "Unsafe assignment of an `any` value"

When using $localize, eslint detects errors and returns two specific ones: Unsafe assignment of an 'any' value and Unsafe any typed template tag. It's quite strange that I seem to be the only one facing this issue while working on the proje ...

Having trouble with passing data using @Input in Angular 5

My goal is to pass a value from app.component.ts named user and assign it to the property of the userComponent called user. Below are the code snippets: app.component.ts import { Component } from '@angular/core'; @Component({ selector: &apo ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

What is the reason for ng cli-generated components having two beforeEach methods in their spec files?

Whenever I execute the command ng c my-component, a spec file is generated with 2 beforeEach functions included. describe('MyComponent', () => { let component: MyComponent; let fixture: ComponentFixture<MyComponent>; beforeEach(a ...

Filtering a Material Table based on numeric ranges in Angular 7

In my Angular 7 project, I am utilizing Material Table. The table in question displays a variety of objects. One of the properties each object has is 'number of promotions,' and I am looking to implement filters based on number ranges (e.g., un ...

Can you explain the meaning and significance of the @Injectable annotation?

Is the use of @Injectable indicating that we are able to inject MyService into other classes, or does it mean that we can inject other classes into MyService? @Injectable({ providedIn: 'root' }) export class MyService { constructor() { } } ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

Angular 2/4: Struggling to refresh child component's view

I need assistance with updating the value of "str" in the child component's view from the parent component. I want to do this by calling the "change()" function in the child component. Here is my code: import { Component } from '@angular/core&ap ...

Utilize NgRx's dispatch method to pass a payload and update the store

Exploring the world of ngRx is a new journey for me. I am currently in the process of establishing a store that will receive updates triggered by actions from components. NgRx create methods are being utilized to craft actions and reducers for this purpose ...