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

Is there a way to verify the presence of a room before transmitting a message to a socket?

sendToSpecificRoom(message: any): void { if(message.roomName){ this.io.sockets.in(message.roomName).emit("eventSent", message); }else{ this.io.sockets.emit("eventSent", message); } } I need to send a message specifically to the ...

Encountering an Issue with Typings Installation in Angular 2 and Algolia Search

Struggling to integrate Algolia Search with my Angular 2 app, I've been following the installation guide at https://github.com/algolia/algoliasearch-client-javascript#install. However, when I run typings install algoliasearch-client-javascript --save ...

Compelled to utilize unfamiliar types in TypeScript generics

When working with a Typescript React form builder, I encountered a situation where each component had different types for the value and onChange properties. To tackle this issue, I decided to utilize generics so that I could define the expected types for e ...

Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows: export class Person{ fname:string, lname?:string } The 'lname' property in the model is optional. To populate the model in a component, I u ...

Create boilerplate code easily in VS Code by using its feature that generates code automatically when creating a

Is there a way to set up VS Code so that it automatically creates Typescript/React boilerplate code when I create a new component? import * as React from "react"; export interface props {} export const MyComponent: React.FC<props> = (): J ...

Arrange gridster items horizontally in angular-gridster2 after reaching the mobile breakpoint

I have successfully integrated angular-gridster2 to organize multiple widgets on a page. The widgets are all aligned and functioning properly when viewed in a desktop browser. However, when the same page is accessed on a mobile device, the widgets stack ve ...

Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize: This is how the Product model looks: import {Optional, Model, Sequelize, DataTypes } from 'sequelize'; /*This is the Product model used to save the data about products* ...

The installation of @types/jquery leads to an unnecessary global declaration of $

In my package.json file, I have the following dependencies defined: { "dependencies": { "@types/jquery": "^3.5.5", } } This adds type declarations through @types/jquery/misc.d.ts, including: declare const jQuery: JQue ...

Angular: Custom Pipes Now Adding Currency Symbol to Model Values

I have encountered an issue involving two currency pipe examples. One example involves using the pipe directly in the view, while the other utilizes the pipe from the TypeScript code side. However, when attempting to submit form data, the value related to ...

What could be the reason for the lack of impact when assigning a [dateClass] in mat-calendar?

I've been trying to customize the appearance of specific days in the mat-calendar component from Angular Material, but I'm having trouble getting it to work. I discovered the dateClass property which seemed like the right solution, but no matter ...

Tips for extracting year, month, and day from a date type in Typescript

I'm currently working with Angular 7 and I'm facing some challenges when it comes to extracting the year, month, and day from a Date type variable. Additionally, I am utilizing Bootstrap 4 in my project. Can anyone assist me with this? Below is ...

Dynamic row insertion in Angular Material table during sorting操作

I utilized Angular material to create a table which looks like this: <mat-table #table [dataSource]="dataSource" matSort> <ng-container *ngFor="let item of displayedColumns; let i = index" cdkColumnDef="{{getColumnName(i)|Formater:'clean&apo ...

Error in MEAN-Stack: Unable to retrieve data from second SQL table on the server

I am currently working on a WebApp using MEANStack, where I utilize Sequelize to interact with SQL Databases. While I have successfully implemented code to read from an SQL Table, I encountered an error when attempting to read from a second SQL Table. The ...

Display the initial MUI components from an array of data in a distinctive manner

Trying to display the content of an Accordion by passing props down through a list array to a component. I have identified the issue but unsure how to call the component and pass the props differently. Below is the code snippet. Code for the parent compon ...

Placeholder for a constructor property method

Currently, I am in the process of writing unit tests for a function that utilizes the twilio-node package to send SMS messages. The specific function I am focusing on testing, both for arguments passed and number of times called, is Twilio.prototype.messag ...

Effortless method for combining PHP API with Angular 2 application on your computer

Currently, I am developing a new Angular 2 application that interacts with a REST API built on PHP. To simulate the data flow, I have generated mock data in a json file for the front end. The PHP REST API was created using MAMP and has been tested succes ...

Having trouble locating the 'tsc-watch' module due to the missing 'typescript/bin/tsc' when running the TypeScript compiler

Encountering the error "Cannot find module 'typescript/bin/tsc' when attempting to run tsc-watch yarn tsc-watch --noClear -p tsconfig.json yarn run v1.22.19 $ /Users/jason/Work/VDQ/VDQApp/node_modules/.bin/tsc-watch --noClear -p tsconfig.json Ca ...

Using Angular 2's ngModel directive to bind a value passed in from an

Using [(ngModel)] in my child component with a string passed from the parent via @Input() is causing some issues. Although the string is successfully passed from the parent to the child, any changes made to it within the child component do not reflect bac ...

Rollup ESM creates faulty imports

I need to package a TypeScript React app as a component in an ES module or UMD, but the ES bundle generated is producing an invalid JS module. When bundling, I receive the following hints. However, I am unable to find a solution for this. (!) Missing glob ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...