The asynchronous function is not returning a value and is currently at a standstill

Looking to retrieve the user data of a logged in user from Google Firebase, I have implemented two methods for this purpose. One method fetches the authState, while the other collects more detailed information under UserInfo.

These methods are encapsulated within a service called UserService:

constructor(private fireStore: AngularFirestore, private fireAuth: AngularFireAuth) {
}

public async getAuthorizedUser(): Promise<UserInfo> {
  console.log('Awaiting Promise');
  const user: firebase.User = await this.fireAuth.authState.toPromise();
  console.log('User', user);
  return this.getUserInfo(user.uid);
}

private async getUserInfo(uid: string): Promise<UserInfo> {
  return this.fireStore.collection('users', ref => ref.where('uid', '==', uid))
             .get()
             .pipe(
               map((item: firebase.firestore.QuerySnapshot) => new UserInfo(item.docs[0].data(), item.docs[0].id))).toPromise();
}

The getAuthorizedUser method is invoked from a button event handler inside a component. The button's HTML code is as follows:

<button mat-button (click)="test()">test</button>

The implementation of the test() method is as below:

async test() {
  console.log('Starting Test');
  const testVariable = await this.userService.getAuthorizedUser();
  console.log('Test', testVariable);
}

Futhermore, the userService refers to the dependency injected UserService.

Upon execution, the console displays:

Starting Test
Awaiting Promise

This seems to indicate that the asynchronous call is not completing as expected, since the logging of

Test

or

User {...}

is missing.

Edit - and partial answer:

After further research on angularfirebase.com, it was suggested that authState should be invoked as

const user: firebase.User = await this.fireAuth.authState.pipe(first()).toPromise();

This caused some confusion, as I had previously used the code snippet below before transitioning to observables. Despite this, my initial code worked fine without any indication of an array being returned by authState:

this.fireAuth.authState.subscribe((user: firebase.User) => {
  if (user) {
    this.getUserData(user.uid);
  }
});

What could be causing this discrepancy, and why does my original solution still function correctly?

Answer №1

toPromise() function generates a promise that is set to resolve once the stream finishes.

If this.fireAuth.authState never completes but continues to emit values, you can employ the first operator to generate a stream that finishes after receiving the initial emitted value. This enables the promise to complete successfully.

On the contrary, the subscribe handler gets invoked for each emitted value separately.

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

typescript leaflet loading tutorial

I'm attempting to replicate the basic example of loading a map with Leaflet in TypeScript, following the guidance on the Leaflet website. I am not utilizing any frameworks like Angular or React. I have installed Leaflet and types through npm. To adher ...

Guide on integrating ng2-bootstrap with .NET Core

I have been attempting to set up ng2-bootstrap in an Angular2 project using the .NET Core template (more information about the template can be found here). However, I am facing difficulties as the ng2-bootstrap components are not functioning properly even ...

Is it possible to utilize enums as keys in a Json structure?

I am currently utilizing TypeScript in conjunction with Node.js (MEAN stack). My aim is to incorporate an enum within the property/schema of a JSON object. An example of the enum would be: enum KeyEnums { A: "featureA", B: "featureB&qu ...

What is an alternative method for authenticating a user to my API through Firebase without relying on traditional login credentials?

As I was developing an API in Express Js for my project, I encountered a challenge. I need to prevent unauthorized access to data from the database, so I decided to implement user authentication using tokens. However, after conducting extensive research ...

In Angular, ensure validation for dropdowns is enforced when the selected value is "yes" in the 2nd dropdown. This means that validation must be applied to the

I am currently working on validation for a set of dropdown menus. There are three dropdowns in total: 1) The first and second dropdowns are mandatory, but for the third dropdown, I need to implement a logic. The logic is that if the value of the second d ...

Utilizing Angular 2: Implementing a template-driven form to send data from a chosen element to the submitting object

Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface: export interface UserModel{ name: string, service: Service ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

Leveraging Angular2 for Azure AD authentication

Currently working with Angular2 and looking to authenticate users through Azure AD. I came across ADALjs, but it's specifically for Angular1. I also found this https://www.npmjs.com/package/angular2-adal#adalService, however it appears to still be in ...

What is the best way to loop through values in a complex JSON structure?

After retrieving data from the "Orders" collection in Firebase Firestore, I am facing an issue with fetching a specific value from the object. The code for fetching data from Firebase is as follows: app.get('/trial',(req,res)=>{ const orders ...

Error message: "The property 'ɵunwrapWritableSignal' is not found on the type 'typeof import_modules/@angular/core/core'". Here is how you can troubleshoot this issue in HTML files

Can anyone help me resolve this error that keeps appearing in all my Angular HTML pages? I am using Node version 14.17.4 and Angular version 15. The error message states: Property 'ɵunwrapWritableSignal' does not exist on type 'typeof impor ...

"Angular allows for the reappearance of an alert even after it has been dismissed

Currently, I am engaged in an Angular project where I am implementing a feature to add objects to a table. However, not all of the object's fields are considered valid, and I need to notify the user through alerts. I am facing an issue where, after di ...

How to include a cancel button within a tab component using Angular Material

I recently implemented a tab component with custom label templates. You can view the code and see how it works in this StackBlitz project. My question is, how can I add a cancel button to the top-right corner of the tabs? I don't need the button to do ...

Encountering an npm package resolution error despite following all of the necessary requirements

error message: ERESOLVE Unable to resolve dependency Issues encountered while resolving: @ionic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52333c35273e332012657c667c60">[email protected]</a> Found: <a href ...

What is the best method for searching a string without considering uppercase or lowercase letters?

Here's a straightforward question I have: I need to search for a specific string match in a query. The code snippet is shown below: const test_name = 'ExAmPlE' const database_resources = await prisma.market.findMany({ where: { na ...

Detecting store changes in a component after dispatching an action in NgRx unit testing can be done

Even after dispatching an action to change the state from 'light' to 'dark', the component is still not reflecting this change and remains as 'light'. Is there a way to detect this inconsistency in the component? Below is the ...

Tips for obtaining the Component instance from the ViewContainerRef.get() method for dynamically created components

Explanation of my current goal successfully add components to a ViewContainerRef (completed) initialize these dynamic components with properties (done) gain access to the dynamically created Component instances for decision-making purposes. The issue at ...

Guide on generating a video thumbnail using JavaScript Application

Searching for a way to easily create a thumbnail from a video for uploading alongside the video itself to a server? I've been looking for JavaScript libraries to simplify the process without much luck. The scenario involves the user selecting a video ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Is the validator in my Angular reactive form malfunctioning?

I have been working on a service where I'm trying to validate the zip code field, but for some reason, the logic (result ? null : { IsInvalid: true }) is not executing. It makes me wonder if there's an issue with the reactive form or if I am usin ...

Challenges with sorting and pagination in Angular 6's material-table

I am facing a challenge in my Angular6 material-data-table application where I need to display and manipulate a complex JSON structure received from a REST endpoint. While the data is successfully displayed, I am struggling to implement pagination and sort ...