Angular Authentication Functionality

I need to create a loggedIn method in the AuthService. This method should return a boolean indicating the user's status. It will be used for the CanActivate method. Here is a snippet of code from the AuthService:

login(email: string, password: string) {
      return this.http.post<AuthResponseData>(
        'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=',
      {
         email,
         password,
         returnSecureToken: true
      }
      )
        .pipe(tap(resData => {
          this.handleAuthentication(
            resData.email,
            resData.localId,
            resData.idToken,
            +resData.expiresIn);
          })
        );
        }

  // tslint:disable-next-line:typedef
    private handleAuthentication(
      email: string,
      userId: string,
      token: string,
      expiresIn: number) {
        const expirationDate = new Date(new Date().getTime() + expiresIn * 1000);
        const user = new User(
          email,
          userId,
          token,
          expirationDate
           );
        this.user.next(user);
}

Answer №1

After a successful login, you can update the variable in the authentication service to indicate true for logged in status and false when logged out. Create a method within the service called getAuthStatus that can be accessed by injecting the authService class into the canActivate constructor. Instead of creating an additional variable, simply check the availability of the user object being created in getLoggedIn status, which can then be injected into the canActivate constructor.

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

Date input using manual typing format

I've implemented the ng-pick-datetime package for handling date selection and display. By using dateTimeAdapter.setLocale('en-IN') in the constructor, I have successfully changed the date format to DD/MM/YYYY. However, I'm facing an iss ...

What is the process of converting exactPageList from any to any[] before assigning it to pagefield?

Encountering an issue with paging on my angular 7 app where I am unable to assign exactpagelist of any type to pagefield of type array. The problem seems to be occurring on the last line of the function totalNoOfPages at this point: this.pageField = this ...

I need to dynamically change the font color based on the data retrieved from the API

I am looking to dynamically change my font color. <div *ngIf="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal'" [ngStyle]="{color:'#ff5454'}" then *ngIf="clientProfileModel.pat ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Is it possible in RxJS to configure a ReplaySubject (or equivalent) that replays the latest messages with a distinctive identifier?

Is it possible to create a generic code that behaves like a ReplaySubject but emits each most recent message with a unique name upon subscribing? In the script below, the current output is... I want this to be logged once ... received the latest bbb 5 I c ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

Is there a way to ensure DRY principles are followed while utilizing Redux Toolkit's asyncThunkCreator?

I have a query related to RTK. I find myself repeating code in my action creators created with createAsyncThunk because I want to be able to cancel any request made. I am thinking of creating a wrapper to streamline this process, but I am facing challenge ...

Eliminate the standard cell padding in nested HTML tables

In my setup, there is a parent table where each td tag in the tr tag contains a child table. Specifically, as shown in the example with Data WS-C3.... in the picture. [![<table class="table table--bordered table--nostripes table-top"> <thead& ...

Angular 5 - Deleting DOM Elements Causes View to Remain Stale

I am experiencing an issue with a tag type search functionality on my website. The search has two columns in the view, with the right column for categories and the left for subcategories. When a user clicks on a category tag, I use buttons to display a sel ...

What could be the reason behind the error related to react-router-dom?

index.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.S ...

Implement push notifications on a React Js web app using Firebase

Trying to implement Firebase push notifications in my React JS application. I have been following the tutorials listed below: https://github.com/pavelpashkovsky/react-fcm Everything is working fine up to the point of receiving the token. However, when I ...

Issues with Angular2 compatibility on macOS Sierra

After updating to the GM version of Mac OS Sierra, I am experiencing issues with Angular2 CLI. The program was already installed and running smoothly before the upgrade. However, now whenever I try to run a command with 'ng' in the terminal, I re ...

What are the reasons behind the compilation failure of the react-sortable-hoc basic example when using typescript?

Take a look at this sample code snippet extracted from the official react-sortable-hoc webpage. import React, {Component} from 'react'; ... // Code snippet goes here ... render(<SortableComponent/& ...

List with pulldown options

I am trying to implement a drop-down list with bullets using Angular 2, JavaScript, and CSS. Although I have managed to create the drop-down list, I am facing difficulty in adding bullets to the list items. Unfortunately, I have found that jQuery and Boot ...

Determine the type of a function to assign to the parent object's property

Consider the following scenario: class SomeClass { public someProperty; public someMethodA(): void { this.someProperty = this.someMethodB() } public someMethodB() { ...some code... } } I need the type of somePropert ...

Tips for resolving the error "Binding element has no default value and initializer provides no value in TypeScript"

I am currently in the process of converting a JavaScript Apollo GraphQL API project to TypeScript. During this migration, I encountered an error related to a user code block: var idArg: any Initializer provides no value for this binding element and the ...

Implementing grid items in CSS Grid that do not stretch the grid row and have a container that is scrollable

Here is my dilemma: I am looking to create a grid with a fixed number of columns (that can be adjusted via javascript) and a variable number of rows, all with equal heights. The rows will be determined by the number of grid items, which are represented a ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...