The authentication value is missing outside the block

Struggling to retrieve the current user information from Firebase google login using angularfire. The issue is why angularfire won't store the current user info. Although the value of this.user is returned within the block, it shows as null outside of it. Looking for some guidance on this.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { FirebaseService } from '../../services/firebase.service';
import * as firebase from 'firebase';
import { AngularFire, FirebaseAuthState } from 'angularfire2';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
  public user: FirebaseAuthState;
  public userProfiles: any;
  public displayName: string;

  constructor(
    public af:AngularFire,
    public flashMessage:FlashMessagesService,
    private firebaseService: FirebaseService,
    private router:Router
  ) {
    this.af.auth.subscribe(user => {
      if(user) {
      // user logged in
        this.user = user;
        console.log('if');
        console.log(this.user);
      }
      else {
      // user not logged in
        // this.user = ;
        console.log('else');
      }
    })
    console.log(this.user);
  }

  ngOnInit() {
    this.af.auth.subscribe((state: FirebaseAuthState) => {
      this.userProfiles = state;
      this.displayName = this.userProfiles.auth.displayName;
      // console.log(this.userProfiles);
    });
    console.log(this.firebaseService.getCurrentUser());
  }

  login(){
    this.af.auth.login();
  }

  logout(){
    this.af.auth.logout();
    this.flashMessage.show('You are logged out',
    {cssClass: 'alert-success', timeout: 3000});
  }

  username(){

  }
}

Answer №1

When attempting to retrieve the value of this.user, I am able to do so within the block but outside of it, a null value is returned. Seeking assistance in resolving this issue.

Examining your code closely

 this.af.auth.subscribe(user => {
  if(user) {
  // user logged in
    this.user = user;
    console.log('if');
    console.log(this.user);
  }
  else {
  // user not logged in
    // this.user = ;
    console.log('else');
  }
})
console.log(this.user);

The method this.af.auth.subscribe( operates asynchronously and does not affect synchronous code. It is similar to

this.user = null;
setTimeout(() => {
  this.user = 'something'
});
console.log(this.user); // null!

Solution

Utilize the user variable inside the subscribe block. You can also invoke functions from within the subscribe block if you need to perform actions on a non-null user.

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

Steps to validate Radio Buttons using ReactiveFormsModule in angularJS2:

Currently, I am a beginner in the world of AngularJS2 and I am focused on mastering validation within an AngularJS2 form using ReactiveFormsModule. However, my progression has hit a roadblock as I am uncertain about how to correctly validate a Radio button ...

How to use a function as the redirectTo parameter in Angular 2+ routing

In my Angular application, I have set up the following route configuration: { path: ParentComponent.path, component: ParentComponent, canActivate: [AuthGuard], children: [ { path: '', pathMatch: 'full', re ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

What is causing the md-menu options to not be injected into my hybrid Angular application?

I am currently troubleshooting an issue in my hybrid Angular/AngularJS application that arises upon reloading. To see a demonstration of this issue, visit this StackBlitz link. The approach I am using to bootstrap AngularJS within an Angular app is largely ...

Show additional information when the button is clicked

I am encountering an issue with my Angular Material expansion panel. I want to automatically expand the accordion if there are validation errors when a button is clicked. However, the problem arises when the user manually minimizes the accordion by clickin ...

How can I nest a kendo-grid within another kendo-grid and make them both editable with on-cell click functionality?

I am facing an issue with my 2 components - trial1 (parent kendo-grid) and trial2 (child kendo-grid). Inside the template of trial1, I referenced the sub-grid component trial2. However, I am encountering an error where trial2 is not recognized inside trial ...

What is the best way to incorporate single quotes within a string literal in JavaScript when constructing SQL queries?

Currently, I am developing a SQL query using Javascript where I pass values. If any value is undefined, I want it to be passed as null. This is how my code looks: const sql = `INSERT INTO MYTABLE( COLUMN1, COLUMN2 ) VALUES( ${param.value1 ?? null}, ...

The current version of "next.js" (version 13.1.6) is experiencing issues with undefined environment variables

I have come across a similar question in the past, however, none of the solutions provided were able to resolve my issue. Currently, I am attempting to utilize environment variables in Next.js with TypeScript, but I keep encountering this error: An argu ...

What is the best way to simulate a worker for testing in Jest?

Currently facing a test challenge: import { convertHeicToPng } from './heicUtils'; class Employee { url: string; onmessage: (m?: any) => void; constructor(stringUrl: string) { this.url = stringUrl; this.onmessage = () => {}; ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Troubleshooting issues with Docker and Angular 2: unable to retrieve data

We are in the process of setting up an Angular 2 application with Docker by following a tutorial available at: https://scotch.io/tutorials/create-a-mean-app-with-angular-2-and-docker-compose Although the application deploys successfully, we encounter an i ...

Lazy loading a child component in Angular 8: A step-by-step guide

In my project, I have a complex component that consists of multiple modals (NgbModal). These modals are connected to various child components. My goal is to implement lazy loading for these child components. Dashboard Module | |--> Dashboa ...

Issue encountered while creating Angular2 application using Visual Studio

I am following this tutorial to create an angular2 app from scratch. However, I'm encountering issues during the build process with TypeScript version discrepancies. Despite installing [email protected] via npm and adjusting the VS Options setti ...

Would it be feasible to rename files uploaded to Firebase within an AngularJS controller using logic?

Is there a way to apply regex to rename uploaded files before saving them to firebase storage? It seems that firebase file metadata does not support this function. I am currently using angularjs and would appreciate any guidance on this matter. ...

Certain features of Bootstrap may not function properly within Angular, yet are fully operational in a traditional HTML file

I recently started exploring Angular and Bootstrap. I created an Angular project and then integrated Bootstrap into it using npm install bootstrap. Afterwards, I experimented with various Bootstrap features on one of the HTML pages within the project. Some ...

What is the best way to incorporate infinite scrolling into my Angular carousel implementation?

After following an amazing tutorial, I was able to create a basic carousel using two directives and one component in Angular. However, the current version of the carousel lacks an 'infinite scrolling' mode, which is something I would like to inc ...

Is it possible to register multiple mini router apps using app.use() in MEAN?

Within my node/express app.js main file, I have established a mini-app router: var router = express.Router(); I pass this router to my controller functions and then export it. Finally, I register the router by using: app.use('/Link', router); ...

Received undefined instead of a Promise or value from the function in Nodemailer

I'm currently exploring cloud functions and trying to implement email notifications for document creation triggers in Firestore. I found a helpful tutorial that guided me through the process, but I encountered an error while analyzing the cloud functi ...

"The limitation of character input in an Ionic Angular input field is not being

After installing the APK on my Android device, I noticed that the input field allows me to enter more than 5 characters even though I have set a maximum length in both the HTML and TypeScript files. This is how my HTML looks: <ion-row id="rowValid ...

How to style the color of a disabled mat-checkbox using Scss

Within my component's SCSS file, I've utilized the following code snippet to define the background color for mat-checkbox when selected: /deep/.mat-checkbox-checked.mat-accent .mat-checkbox-background, .mat-checkbox-indeterminate.mat-accent .mat ...