What could be causing my function to not provide the expected output?

Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service.

login.page.ts:

ngOnInit(){
  console.log(this.auth.getRole());
}

auth-admin.service.ts:

Initial Approach

getRole() {
     this.afAuth.onAuthStateChanged(user => {
       if (user) {
         this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
         .get()
         .then(userProfileSnapshot => {
           let isAdmin = userProfileSnapshot.data().udbid.role;
           return isAdmin;
         })
       }
     });
   }

CONSOLE LOG

undefined

In my second attempt, I added a console message before returning the value. This time, the desired value showed up in the console eventually, but there was still an initial result of "undefined" before that. Strangely, the function never actually returned the value.

Second Attempt

 getRole() {
     this.afAuth.onAuthStateChanged(user => {
       if (user) {
         this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
         .get()
         .then(userProfileSnapshot => {
           let isAdmin = userProfileSnapshot.data().udbid.role;
           console.log(isAdmin)
           return isAdmin;
         })
       }
     });
   }
   

CONSOLE LOG:

undefined

Admin

Answer №1

Consider implementing the getRole function as an asynchronous operation.

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

My Vuefire firestore() function is failing to properly bind my data

I am encountering a problem that has me stumped. VueFire worked perfectly in another application I developed, but for some reason it is not binding correctly in my current one. Below you can see the code snippet on the page where the firestore() function i ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Refreshing the view in Angular2 after rejecting changes in a text input field

I have multiple text areas in an array, each of which can be edited individually and the changes can either be saved or discarded. Every textarea has an associated object to monitor the modifications and enable/disable specific buttons. While everything se ...

What steps do I need to follow to develop a checkbox component that mirrors the value of a TextField?

I am working with 3 components - 2 textfields and 1 checkbox Material UI component. My goal is to have the checkbox checked only when there is a value in one of the textfield components. What would be the most effective way to achieve this functionality? ...

Assessing the validity of a boolean condition as either true or false while iterating through a for loop

I am facing an issue that involves converting a boolean value to true or false if a string contains the word "unlimited". Additionally, I am adding a subscription to a set of values and need to use *NgIf to control page rendering based on this boolean. &l ...

Dynamically Disabling Form Control in Angular 2

There is a basic form with two form controls that initially have required validation. In addition to the form controls, there is a button in the template. When this button is clicked, it triggers a change in the behavior of the form group. Both form contr ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Encountered a hiccup during the installation of ssh2-sftp-client on Next.js

I'm looking for a way to save uploaded files in my domain's storage using SFTP. I came across the multer-sftp package, but when I attempted to run the command yarn add multer-sftp ssh2-sftp-client, I encountered a strange error with the second pa ...

Unable to retrieve the user information using the UID of the current user in Ionic 3

Attempting to retrieve the username of a user by utilizing the current user's UID. The UID is saved in both Firebase database and authentication. this.userid=firebase.auth().currentUser.uid; this.username=firebase.database().ref('Users/'+ ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

Encountering an unexpected token while trying to use createUserWithEmailAndPassword in firebase/auth with Next.js and TypeScript left Jest puzzled

I have been working on integrating Firebase authentication into my Next.js project (using TypeScript), but it appears that there are configuration issues with Firebase causing my Jest tests to fail. Here are the key configuration files: jest.config.js : ...

Incorporating AWS-Cognito into Angular 2

I'm currently diving into the world of building web applications using Angular and AWS. My initial focus is on setting up authentication with AWS-Cognito. However, I've encountered some hurdles while trying to import and utilize the AWS-Cognito S ...

An issue with the "req" parameter in Middleware.ts: - No compatible overload found for this call

Currently, I am utilizing the following dependencies: "next": "14.1.0", "next-auth": "^5.0.0-beta.11", "next-themes": "^0.2.1", In my project directory's root, there exists a file named midd ...

Contrasting between betting text and console error logging in Angular

Currently working on an Angular application and exploring the best practices for error logging. I'm pondering whether to opt for console logging or text-based logging. Text-based logging seems beneficial as it stores historical error data on the serv ...

Angular: Merge two Observables to create a single list and fetch the combined data

I am currently working on creating a function that returns an observable with a list, compiled from several observables. I feel like I am very close to finding the solution because the debugger stops right before displaying the list. Here is my code: ts t ...

Sort products by category upon loading of the category page in Angular

I am currently working on an angular web application that showcases various categories from the category model. The category model is linked as a foreign key to the products model. My goal is to implement a feature where users can filter and view all the p ...

I am unable to add a new property to the request object in the Express framework

My goal is to add a new property to the request object in typescript. Here's the code snippet I'm using: import { request, Request, response, Response } from "express"; ((req: Request, res: Response) => { console.log(req.user); ...

Encountered an issue with the core-js postinstall script, causing a failure

I encountered the following errors while attempting to install node modules in an existing Angular project. The installation is being carried out on a Windows machine (Win32 X64). > [email protected] postinstall node_modules\babel-runti ...

Encountering issues in Angular 2 when attempting to pass data into root component through ng-content and binding. Objective: Creating a reusable form component

I currently have a .NET MVC application and I'm looking to integrate Angular 2 into it. The structure of my page is as follows: <html> <head>css imports and jquery imports</head> <body> <div> a bunch of table ...