Displaying buttons based on the existence of a token in Angular - A guide

Can you assist me with a coding issue I'm facing? I have implemented three methods: login, logout, and isAuthenticated. My goal is to securely store the token in localStorage upon login, and display only the Logout button when authenticated. However, after logging in and reloading the page, all three buttons are still visible instead of just the Logout button. Even though the token is stored in localStorage, the logic seems to be off. Could you help me identify the problem and suggest how to adjust the logic for the logout functionality as well? Thank you in advance.

component.ts

export class AppComponent implements OnInit {

  public isAuthenticated: boolean = false;

  constructor(private router: Router, private authService: AuthService) {}

  ngOnInit(): void {
    this.isAuthenticated = this.authService.isAuthenticated();
    this.authService.isAuthenticatedSubject.subscribe(isAuthenticated=> {
        this.isAuthenticated = isAuthenticated;
    });
  }

  logout(): void {
    this.authService.logout().subscribe(() => {});
  }
}

component.html

<div class="buttons">
    <button *ngIf="!isAuthenticated"> Login </button>
    <button *ngIf="!isAuthenticated"> Signup </button>
    <button (click)="logout()" *ngIf="isAuthenticated"> Logout </button>
</div>

auth.service

export class AuthService {

  public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor(private httpClient: HttpClient) {}

  public login(body: LoginModel): Observable<SignupLoginResponseModel> {
    return this.httpClient.post<SignupLoginResponseModel>(`${environment.apiUrl}/auth/login`, body)
      .pipe(
        tap((response) => {
          localStorage.setItem('access_token', response.access_token);
          this.isAuthenticatedSubject.next(true);
        })
    );
  }

  public logout(): Observable<Object> {
    return this.httpClient.post(`${environment.apiUrl}/auth/logout`, {})
      .pipe(
        tap(() => {
          localStorage.removeItem('access_token');
          this.isAuthenticatedSubject.next(false);
        })
    );
  }

  public getToken(): string {
    return localStorage.getItem('access_token')!;
  }

  public isAuthenticated(): boolean {
    const token = this.getToken();
    return !!token;
  }

}

Answer №1

Set the value of isAuthenticatedSubject to true if there is a token, otherwise set it to false.

public isAuthenticatedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(Boolean(getToken()));

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

Opening an external link from the Side Menu in Ionic4: A step-by-step guide

In my Ionic project, I have implemented a side menu in the app.html file that is accessible throughout the entire application. This menu contains items with links that need to be opened externally. However, when trying to open them using InAppBrowser, an e ...

ngIf is not refreshing my template

Within my Angular2 application, I have a Component that takes an array as input and utilizes a service to retrieve the Latitude and Longitude for each entry in the array. This involves making multiple asynchronous calls to the service using Promises. expo ...

Describing a function in Typescript that takes an array of functions as input, and outputs an array containing the return types of each function

Can the code snippet below be accurately typed? function determineElementTypes(...array: Array<(() => string) | (() => number) | (() => {prop: string}) | (() => number[])>) { /// .. do something /// .. and then return an array ...

What is the best way to allow a C# Web API method to be accessed from any origin?

My C# Web API includes the following method: public JsonResult PlanItems(string sessionId) { Response.Headers.Add("Access-Control-Allow-Origin", "*"); DTDBDataService svc = new DTDBDataService(_db); VM.PlanItems = svc.GetPla ...

Promise<IDropdownOption[]> converted to <IDropdownOption[]>

I wrote a function to retrieve field values from my SPFx list: async getFieldOptions(){ const optionDrop: IDropdownOption[]= []; const variable: IEleccion = await sp.web.lists.getByTitle("Groups").fields.getByTitle("Sector").get ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

The utilization of ~ (tilde) for SCSS file imports seems to be malfunctioning in Angular 6

Having some issues with importing SCSS files in Angular6, need clarification on a couple of things: If I import my partials once in the global src/sass/styles.scss, do I still need to import them individually in all component.scss files? Is there a way t ...

The Angular application shell build has produced two new folders within the dist directory. I'm curious about their purpose and how they can

Whenever I execute the ng run my-app:app-shell -c production command, it creates 2 folders within the dist directory - one for the browser and one for the server. Now, I find myself with 2 different commands to use: npm build --prod (for a regular build) ...

Fixing the issue of the Put method not successfully updating MongoDB when using Angular7 with NodeJS on the

Currently, I am facing an issue with my Angular7 application that is connected to NodeJS and MongoDB on the backend. After testing the put method using Postman, it seemed to work perfectly. However, the problem seems to be within the Angular service compon ...

Tips for resolving errors in Angular controls

Setting custom errors in Angular is straightforward with this code snippet: this.form.controls['field'].setErrors({same:true}); However, the process for removing custom errors is not as obvious. Does anyone know how to accomplish this? Are ther ...

Steps to resolve the error message 'Uncaught Error: Unable to find all parameters for AuthService: (?)'

An issue is arising when the application is initiated. No errors are displaying in the terminal, but they appear in the browser console. The last action taken was importing JwtHelperService from '@auth0/angular-jwt'. The project involves Nodejs, ...

Navigating Angular modules - a different perspective

I am brand new to angular routing and lazy loading modules. ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login-admin/admin-dashboard' Error: Cannot match any routes. URL Segment: 'login-admin/admin-d ...

Angular 2 integration for Oauth 2 popup authorization

I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth proc ...

Strategies for modifying the bound value in Angular with an observable object

I am attempting to convert the offset value for a time object in the URI, which is stored in an observable object. The issue I am encountering is: ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checke ...

I am interested in incorporating a personalized class into the Kendo UI for Angular TabStrip

<kendo-tabstrip (tabSelect)="onTabSelect($event)"> <kendo-tabstrip-tab title="Paris" [selected]="true"> <ng-template kendoTabContent> <div class="content"> ...

Intercepting Nested Requests in a Nest.js Application

Can you explain how to incorporate a nested interceptor in Nest.js? I currently have two interceptors: UsersInterceptor and PostsInterceptor UsersInterceptor: @Injectable() export class UsersInterceptor<T> implements NestInterceptor<T, Response& ...

AmCharts issue in NextJS - Unusual SyntaxError: Unexpected token 'export' detected

Encountered an error while trying to utilize the '@amcharts/amcharts4/core' package and other amchart modules in a NextJS project: SyntaxError: Unexpected token 'export' After searching through various resources, I came across a helpf ...

An error has occurred: The repository is not clear. Kindly commit or stash any modifications before proceeding with the update

I am looking to upgrade my Angular 6 project to Angular 8. First step is to execute npm install -g @angular/cli@latest (this code works fine). Next, run ng update @angular/cli @angular/core. However, I encountered the following error: The repository i ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...