Ensuring User Authentication in Angular with Firebase: How to Dynamically Hide the Login Link in Navigation Based on User's Login Status

After successfully implementing Angular Firebase email and password registration and login, the next step is to check the user's state in the navigation template. If the user is logged in, I want to hide the login button and register button. I tried searching for tutorials on how to achieve this and came across using AuthService and AuthInfo as shown here:

https://github.com/angular-university/angular-firebase-app/blob/master/src/app/shared/security/auth.service.ts

The challenge I'm facing is that these tutorials involve a lot of promises and concepts that I'm not familiar with, which can be confusing. I'm looking for a simpler approach and guidance from someone who can assist me.

Below are snippets of my current code:

Navigation -

<ul class="nav navbar-nav">
    <li><a routerLink="" routerLinkActive="active">Home</a></li>
    <li><a routerLink="login" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Login</a></li>
    <li><a routerLink="register" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Register</a></li>
    <li><a routerLink="quiz" routerLinkActive="active">Quiz</a></li>
</ul>

Auth service file containing user creation and login logic for Firebase -

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    private user: Observable<firebase.User>;
    constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
        // Logic for initializing user

        ...

    }

    // Methods for logging in and registering users

    ...

}
... (more content follows)

Answer ā„–1

To ensure persistence, it is recommended to utilize session handling for consistent user authentication even after page refreshes.

Simply create and manage a property like loggedIn within your AuthService service -

public loggedIn = false;

constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
    this.loggedIn = !!sessionStorage.getItem('user');
}

// Save the current user's email in the session upon successful login
setCurrentUser(email: String): void {
    sessionStorage.setItem('user', email);
    this.loggedIn = true;
}

// Retrieve the email of currently logged in user from session
getCurrentUser(): string | any {
    return sessionStorage.getItem('user') || undefined;
}

// Clear the session data when user logs out
logout() {
    sessionStorage.removeItem('user');
    this.loggedIn = false;
    // ... additional logout logic here
}

// Method to determine if a user is logged in
isLoggedIn() {
    return this.loggedIn;
}

Your updated method logUserIn would look like this -

logUserIn(email, pass) {
    firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log("error" + error);
    })

    if (this.userDetails) {
        email = this.userDetails.email;
        console.log("hello im user" + " " + email);
        // Save user details in session here --->
        this.setCurrentUser(email);
    } else {
        console.log("not working");
    }

    this.router.navigate(['']);
}

When logging out, remember to call the logout() method as demonstrated above.

Lastly, include this check in your HTML template -

<li><a routerLink="login" routerLinkActive="active" *ngIf="!auth.isLoggedIn()">Login</a></li>

Answer ā„–2

Here's a more straightforward method to achieve this task. For detailed instructions, refer to the official Github documentation at: https://github.com/angular/angularfire/blob/master/docs/auth/getting-started.md

The steps you need to follow are...

myPage.component.ts

import { AngularFireAuth } from '@angular/fire/auth';
//...
constructor(public authFire: AngularFireAuth) { }

myPage.component.html

<div *ngIf="(authFire.user | async)">User is currently logged in</div>
<div *ngIf="!(authFire.user | async)">User is currently logged out</div>

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

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

What is the best way to implement react-password-checklist with zod?

I've been trying to utilize the react-password-checklist library to inform users if their password complies with the rules set in zod's schemaUser. However, I'm facing challenges in implementing this feature successfully. Note: I am using zo ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Encountering a multitude of challenges when attempting to seamlessly integrate aframe into an angular2 project, especially when incorporating unit tests

I'm encountering issues with integrating aframe 0.7.0 effectively into my angular 4.3.6 (angular-cli 1.0.0) project. The error messages I am receiving include: Chrome 61.0.3163 (Windows 10 0.0.0) LOG: '%cA-Frame:warn %cPut the A-Frame <script ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

The array contains data, yet the console is displaying a length of 0 for the array

Iā€™m experiencing an issue with my code that involves a files array. Whenever I add a new file, it displays the incorrect length of the array. Strangely, if I use setTimeout to check the length, it shows the correct one. console.log('row.myDocuments ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

What is the process for retrieving information from Sanity?

Having trouble with creating a schema and fetching data from sanity. The console log is showing undefined. Not sure where I went wrong but suspect it's related to the schema creation. Testimonials.tsx interface Props { testimonial: [Testimonial] ...

Storing response data as a variable in TypeScript with Angular 2 can be achieved by declaring a variable

I am unfamiliar with TypeScript and need assistance. After performing a POST request, I received an _id that I now need to use to execute a PUT function for play pause. When the play pause button is clicked, the response should be sent to the server. Below ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...

Angular 2, using Jasmine and Karma for testing, encountered an error with the HTTP testing API, which returned an error message stating: {"isTr

I've set up an http test case for my Angular2 app using Jasmine-Karma and encountered an API error: Uncaught API Error. Scenario: I'm trying to test an http service for my Angular2 App using Karma-Jasmine, and I've implemented the method be ...

What is the proper way to declare app.use using TypeScript with the node.js Express module?

I am working on a node.js app that utilizes typescript with express. In my code, I have defined an error middleware function as shown below: app.use((error:any, req:Request, res:Response, next:NextFunction) => { res.status(500).json({message:error.m ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Utilizing a function within the catchError method

A function has been defined to handle errors by opening a MatSnackBar to display the error message whenever a get request encounters an error. handleError(err: HttpErrorResponse) { this.snackBar.open(err.message) return throwError(err) } When subs ...

Troubleshooting Angular 2: (keyup) event not functioning on Tour of Heroes Tutorial

I am currently working on a tutorial for the tour of heroes, and I have encountered an issue with the (keyup) event in my project. What seems to be happening is that when I input the first letter, Angular sends a request, but subsequent key presses do not ...

The potential object null may lead to an absence of the 'value' property in the type 'EventTarget'

I am facing a problem that I am unable to resolve. The error in my HTML reads: Object is possibly 'null' and Property 'value' does not exist on type 'EventTarget'. HTML <select [(ngModel)]="selectedProvincia" (ch ...

Trying to automatically select a checkbox upon page load in Angular 6

When the page loads, I want to automatically check a checkbox. Here is my component: var user = ViewprojectComponent.featuresList1; this.rules_id = user[0]; for(let i = 0; i <= this.rules_id.length; i++) { var checkedOn1 = this.rules_id[i]; this.Ru ...

Allow users to upload .docx and .xlsx file types with an input field of

I'm currently working on a file upload feature that requires checking for allowed file extensions. The two file extensions allowed are .docx and .xlsx. I've noticed that when I try to log the file extension using console.log, it doesn't prin ...