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

What is the best way to showcase a variable from a typescript file in an HTML file with Angular?

In my TypeScript file, I have the following function: ngOnInit() { if (sessionStorage['loyalPage']) { this.page = Number(sessionStorage['loyalPage']); } this.webService.getLoyalPlayers(this.pag ...

An error has occurred in the tipo-struttura component file in an Angular application connected with a Spring backend and SQL database. The error message indicates that there is a TypeError where the

Working on my project that combines Spring, Angular, and MYSQL, I encountered a challenge of managing three interconnected lists. The third list depends on the second one, which in turn relies on user choices made from the first list. While attempting to l ...

What is the best way to obtain an array of downloadable links from Firebase Storage and then store it in an object to be saved in a MongoDB

I have a question regarding setting an array of image links to my createAd function in order to store the result into MongoDB database. Despite getting the image links through the getLinks function as seen below, I always end up with an empty [] array for ...

What's the best way to determine the event type when a mouseDown occurs in React while working on a canvas?

I've been tackling the challenge of incorporating the <canvas /> element into a react project, but I'm encountering difficulties with determining the appropriate event type for it. In my quest for answers, I stumbled upon this insightful ar ...

Runtime AbstractControl in Angular 2

Following the guidance provided in this answer here, I attempted to incorporate an "Add more" feature into my Angular 2 application. The associated project can be found on this link. However, in order to initialize the project, I had to temporarily comment ...

Utilizing Angular http.post to retrieve data from Cloud Function via POST request

Trying to send a POST request to a Google Cloud Function from Angular using @angular/common/http. The documentation for Angular http v7 lacks comprehensive examples, with no information on how to include data or objects in the request. Angular code snippe ...

Encountering a GitHub REST API CORS issue while attempting to fetch a public repository's git archive

I'm currently working on developing an Angular application that will be hosted on my GitHub pages using a custom verified domain. Below is the code I am using to call the GitHub API in order to obtain the zip archive of one of my (public) repositori ...

I am having trouble with the TypeScript compiler options not being detected in Visual Studio 2015

After creating an ASP.NET 5 Empty Website project in Visual Studio 2015, I set up a tsconfig.json file with the following settings: { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false ...

Facing issues during the unit testing of an angular component method?

I'm facing an issue with a unit test that is failing. Below is the code for reference: Here is my typescript file: allData: any; constructor(@Inject(MAT_DIALOG_DATA) private data, private dialogRef: MatDialogRef<MyComponent>, priva ...

Steps to include a horizontal divider in the footer section of an angular-material table

Is it possible to add a line between the last row (Swimsuit) and the footer line (Total)? If so, how can I achieve this using Angular 15? https://i.stack.imgur.com/581Nf.png ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

Issue with Vue 3 / Typescript: Unable to locate variable name in template

When working with Vue 3 and Typescript, I encountered an error that says "Cannot find name" when trying to reference a data variable in a certain area. How can I resolve this issue? Attached is a screenshot for reference: . Thank you in advance. ...

What is the best method for regularly importing large JSON datasets into Cloud Firestore?

I have a task to import a large JSON file containing 180k records. Currently, I am able to upload only 500 records per run using the code below, but I need to find a way to efficiently upload all 180k records periodically. My Objectives: Successfully par ...

How to update path parameters in Angular 2 without triggering a redirect

Is there a way to update the URL Path in Angular 2 without actually redirecting the page? I am familiar with accessing query parameters using ActivatedRoute's queryParamMap Observable, but how can I change these values and have them reflected in the ...

Configuration error with MultiCapabilities

Encountering an issue while utilizing multiCapabilities with two web browsers (Firefox and Chrome). Below is a snippet from my configuration: exports.config = { allScriptsTimeout: 11000, seleniumAddress: 'http://localhost:4444/wd/hub', b ...

Exploring how to set dropdown menu width for Angular2 mat-select options

Currently, I am using the angular2 mat-select control and facing an issue with the width and position of its dropdown list menu. By default, it is wider and overflows the element on both sides by a few pixels. I have not found any option for adjusting the ...

Execution of the RxJS pipe Finalize operator initiated prior to Observable finalization

After updating the detailed information of users, I attempted to retrieve the updated user list. Initially, I used this.mediaService.updateImports(): Observable<any> to update the user details. Next, I tried displaying the updated user details us ...

Firing an Event with a specific target value using Jasmine

Is there a way to trigger a change event in a Jasmine unit test with the inclusion of a target.value? The component being tested contains a method similar to this: @HostListener('change', ['$event']) onChange(event) { const value = e ...

tips for utilizing a variable for inferring an object in typescript

In my current code, I have the following working implementation: type ParamType = { a: string, b: string } | { c: string } if ('a' in params) { doSomethingA(params) } else { doSomethingC(params) } The functions doSomethingA and doSomething ...

What is the best way to pass a specific property from a parent component to a child component in Angular when a button is clicked?

Hey there, I'm looking for a way to pass a single property (groupId) from a parent component to a child component. In this case, my child component is using ngx-bootstrap modal. Is there a solution available for this scenario? Essentially, I need to i ...