The issue of Angular 6 view failing to display accurate data upon page load

In my Angular 6 application, I've implemented a login feature using Firebase's Google login. The interface includes a button labeled Login when the user is logged out, and changes to Logout with the current email address displayed when the user is logged in.

Here is an example of the code:

<p *ngIf="isLoggedIn()" class="text-white" style="margin-bottom: 0; padding-left: 10px">{{ afAuth.auth.currentUser.email }}</p>
<button *ngIf="!isLoggedIn()" class="btn btn-danger" type="button" (click)="login()">Log In</button>
<button *ngIf="isLoggedIn()" class="btn btn-danger" type="button" (click)="logout()">Log Out</button>

constructor(private afAuth: AngularFireAuth) {
}

isLoggedIn() {
  return this.afAuth.auth.currentUser;
}

login() {
  try {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
  } catch (e) {
    console.log(e.message);
  }
}

logout () {
  try {
    this.afAuth.auth.signOut().then(() => {
      this.hideAllViews();
    });
  } catch (e) {
    console.log(e.message);
  }
}

The functionality works correctly, but there's an issue where if a user is already logged in and refreshes the page, it initially shows the Login button instead of displaying the email and Logout button. Once the user interacts with the page, the correct state is shown.

It appears that the HTML loads before checking the isLoggedIn() method.

To address this, I've added the following workaround inside the constructor:

setTimeout(function () {
}, 

I'm seeking guidance on the best way to resolve this issue in line with Angular practices.

Answer №1

To ensure that your variable currentUser is initialized, monitor the callback function for onAuthStateChanged().

/* Ensure you have imported Firebase */
import * as firebase from 'firebase/app';

<p *ngIf="isLoggedIn()" class="text-white" style="margin-bottom: 0; padding-left: 10px">{{ afAuth.auth.currentUser.email }}</p>
<button *ngIf="!isLoggedIn()" class="btn btn-danger" type="button" (click)="login()">Log In</button>
<button *ngIf="isLoggedIn()" class="btn btn-danger" type="button" (click)="logout()">Log Out</button>

constructor(private afAuth: AngularFireAuth) {
}

/* Use the callback to determine when the variable is initialized */
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // Perform actions when a user is logged in
  } else {
    // Handle cases where no user is logged in
  }
});

login() {
  try {
    this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
  } catch (e) {
    console.log(e.message);
  }
}

logout () {
  try {
    this.afAuth.auth.signOut().then(() => {
      this.hideAllViews();
    });
  } catch (e) {
    console.log(e.message);
  }
}

Answer №2

Your solution is a clever workaround, but the recommended approach is to utilize lifecycle hooks such as ngAfterViewInit

ngAfterViewInit() {
   this.checkLoginStatus();
}

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

Ensure that any modifications made to an Angular service are reflected across all components that rely on that service

I am currently in the process of replicating a platform known as Kualitee.com, which serves as a test-management tool utilized by QA Engineers. Within Kualitee, users can access multiple projects, each containing various test cases and team members. The ab ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises wh ...

Encountered an issue with npm install where it cannot read the property 'startsWith' of null

I have been trying to find a solution to this problem everywhere, but without success. Most answers suggest that there might be an issue with the proxy settings. Every time I attempt to use npm install -g package-name, an error occurs. npm ERR! Cannot rea ...

What steps do I need to take to ensure the CSS hover effect functions properly?

After conducting a simple test underneath the main divs, I found that it works as intended. However, the primary one is not functioning properly. I attempted to apply the class "services-icon" to the div containing the image, but it still did not work. I ...

How to extract the first initials from a full name using Angular TypeScript and *ngFor

I am new to Angular and still learning about its functionalities. Currently, I am developing an Angular app where I need to display a list of people. In case there is no picture available for a person, I want to show the first letters of their first name a ...

Is there a way to handle specific email format designs with PHP?

When trying to send an email with specific shipping information and tracking numbers, the formatting appears strange. Here is the desired format: Dear xyz , Per your request, this email is to no ...

Learn how to display separate paragraphs upon clicking a specific item

New to coding and eager to learn, I have recently started exploring HTML, CSS, and basic JavaScript. In my journey to enhance my skills, I am working on building a website for practice. One particular page of the site showcases various articles, each acc ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Tips for dynamically updating the value of a variable in Vue by importing a JavaScript file

There is a file for an app that imports ymaps.js where YmapsComponent.vue is declared. import '../js/ymaps.js'; import { createApp } from 'vue'; const app = createApp({}); import YmapsComponent from './components/YmapsComponent.vue ...

Jquery code that mimics pressing a key downwards is not functioning properly to execute a keyboard shortcut

I would like to express my gratitude in advance for any time and effort dedicated to this matter. So, here's the situation: I have a script that is meant to simulate a key press event after 3 seconds once the page is loaded. The goal was to trigger a ...

ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

"Exploring the world of npm packages alongside the powerful angular-cli tool

Is it better to package angular2 components in an npm module with the source files (*.ts, *.css, *.html) or the webpack compiled version for use in applications compiled with angular-cli@webpack? What should actually be published in the npm package? The r ...

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

Executing a controller method in AngularJS when redirecting a page

I am currently working on an app using Cordova/Phonegap, Ionic, and AngularJS. One challenge I am facing is trying to call a method from a controller inside my app when redirecting to another HTML page (secondPage.html). This particular method (secondMetho ...

Tips for displaying personalized data with MUI DatePicker

I need to create a React TypeScript component that displays a MUI DatePicker. When a new date is selected, I want a custom component (called <Badge>) to appear in the value field. Previously, I was able to achieve this with MUI Select: return ( ...