How do I retrieve the user's login status from auth.service.ts in Angular's guard?

When using canActivate in history.guard, how can I verify if the user is logged in or not? The console always returns false as a value. Do I need to create a new function in auth.service or make edits directly in history.guard? Is there an alternative method to using subscribe?

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';

@Injectable()
export class AuthService {

  logger = new BehaviorSubject<Object>(false);
  referralRoute: string;

  constructor(
    private router: Router,
    private api: ApiService
  ) {
  }

  // Other methods are omitted for brevity

}

history.guard.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../../core/service/auth/auth.service';

@Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
  checkUserLogin: boolean;
    constructor(
        private router: Router,
        private auth: AuthService
    ) {}
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const checkUserLogin = this.auth.subscribeLogger().subscribe(
          (data: any) => {
            this.checkUserLogin = data;
          }
        );
        if (!this.checkUserLogin) {
          return this.router.navigate(['mypage']);
        }
        else {
          return this.checkUserLogin;
        }
    }
}

history.module.ts

import { NgModule } from '@angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HistoryGuard } from  './history.guard';

const routes: Routes = [
  {
    path: '',
    component: HistoryComponent,
    canActivate: [HistoryGuard]
  },
  {
    path: ':id',
    component: HistoryItemComponent,
    canActivate: [HistoryGuard]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }

Answer №1

Hello! Here is my approach to implementing the AuthGuard. Simply check if there is a JWT token stored in the local storage, as it indicates whether a user is logged in or not. Remember to delete the JWT token from localStorage upon logout.

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

// Auth service 

isLoggedIn() {
    return Boolean(this.getToken());
}

getToken() {
    return this.localStorage$.retrieve('authenticationToken');
}

logout() {
    this.localStorage$.clear('authenticationtoken');
}

Answer №2

Check out the correct structure for your canActivate function:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
  return this.auth.subscribeLogger().pipe(
    tap(login => {
      if(!login) {
        this.router.navigate(['mypage']); // Redirect to 'mypage' if user is not logged in
      }
    })
  );
}

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

Using Node.js to retrieve JSON objects from an API call with node-postgres

After carefully following the instructions on connecting to my postgres table using async/await provided at , I have successfully set up routes to retrieve and display user data. By accessing localhost:3000/users/1, the browser displays the JSON string fo ...

If two requests are made at the same time, they will both yield identical results

Encountering an issue where running two separate HttpClient requests to my Spring Boot backend yields the same result for both requests (the first request's result). This occurs approximately 30% of the time: //request 1 with url_1= "http://local ...

What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code: <p id="test">Some text</p> Here is the JavaScript code I am using: var myVar = document.getElementById('test' ...

Focusing on the specific properties of a type that serve as index signatures

Currently, I am in the process of developing a type definition set that functions on a user-provided type representing the model of their "state". One crucial task I must accomplish is narrowing down the types of their model as I generate new types that w ...

Can someone explain the purpose of this code snippet: `const { foo = "bar" } = "baz"`?

I came across this code not too long ago and had trouble finding the answer online, so I'm turning to you for help. The specific code snippet is from a webpack configuration file: const { NODE_ENV = 'production', } = process.env; Appreci ...

Using Object Value as Variable instead of String in JavaScript/React

When working with React & JavaScript, I am storing an input name as a string in an object: window.ObjectOne = { ObjectOneKey: "MyInputName", } The input name can be an object path like "Object.FirstName" or a variable name "MyVariableName" What I am at ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

Ways to evaluate two sentences based solely on the spacing in their dynamic sections

I am tasked with comparing two sentences. The first sentence is stored in a database and looks like this: var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd" The second sentence, which comes from the customer, is as follows: &q ...

jQuery form validation not functioning as expected

I'm attempting jQuery form validation but encountering issues with the desired functionality. I would like the border of an input to turn red when it's empty upon focus out. Alternatively, I aim to incorporate the "has-danger" bootstrap class to ...

npm - Configuring the maximum memory usage in npm

I encountered an error message while trying to build my Angular project, The error states: "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" I read somewhere that adjusting the max-old-space-size in npm could resolve this issue. How ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

What is the significance of setting multi:true in Angular 4 providers?

Utilizing HTTP_INTERCEPTORS in angular4 involves creating a HttpServiceInterceptor class that implements the HttpInterceptor interface and defines the intercept method. To register the provider for HTTP_INTERCEPTORS, the following code is used: providers: ...

Instructions on utilizing *ngFor for every category I have

Seeking assistance with a specific issue. I currently have four labeled tabs, each containing projects. My goal is to ensure that when I save a project, it remains in the same tab where I initiated the save operation, rather than appearing across all tabs. ...

AngularJS Enhanced Multi-Level Table

Currently, I'm attempting to display 3 tables on a single page that pull data from the same array but filter it using ng-repeat. I followed a similar table format from another source and you can view my JS Fiddle Link here: http://jsfiddle.net/6Texj/1 ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

Implementing 'Load more...' in Rails for infinite scrolling instead of traditional pagination

I currently have a collection of items and have been utilizing the will_paginate gem. However, I am interested in implementing a "load more..." feature at the end of the list. Is there a straightforward way to achieve this with will_paginate, or should I e ...

How can you loop through an array of objects in TypeScript without relying on the traditional forEach

Currently, I'm working on an array of objects with the following structure. [ { "matListParent": "CH", "dParent": "CUST1", "isAllSelected": true, "childItems&qu ...

The ng-class condition is in flux, however, the new style is not being

Attempting to modify the background of the pane in an Ionic application based on the condition of the ng-class as shown. Changing the condition in the code and refreshing the page manually works correctly, but updating the condition from user input does ...

Ending the jQuery Modal box

Struggling to create a simple modal on my own, and I'm facing some difficulties (probably because I'm more of an expert in jQuery - but let's not dwell on that too much). This is the HTML markup I have: <div id="modal-boxes"> < ...

Having trouble with clearInterval in my Angular code

After all files have finished running, the array this.currentlyRunning is emptied and its length becomes zero. if(numberOfFiles === 0) { clearInterval(this.repeat); } I conducted a test using console.log and found that even though ...