The user authentication service indicates that no user is currently logged in

Currently, I am working on implementing a route guard to distinguish between authenticated users and guests. In order to achieve this, I have created an auth-guard service along with an auth service. Although the user data is successfully stored in the local storage, when I use console.log() to print out the user object, it displays as null.

auth.service.ts

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(public storage: Storage) {}
  // ...
  public isAuthenticated(): boolean{
    const user: any = localStorage.getItem('user');
    console.log(user); // null in console
    if (user !== null
      && user.token !== null
      && user.token_deadline !== null
      && new Date(user.token_deadline) > new Date())
      return true;
    return false;
  }
}

auth-guard.service.ts

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


@Injectable()
export class AuthGuardService implements CanActivate {

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

  }

  canActivate(route: ActivatedRouteSnapshot): boolean {

    return(this.authService.isAuthenticated())
  }
}

Answer №1

Incorporating Storage as storage, however, within your function you are referring to localStorage. This appears to be incorrect. Shouldn't it be this.storage instead?

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(public storage: Storage) {}
  // ...
  public isAuthenticated(): boolean{
    const user: any = this.storage.getItem('user'); // <-- here
    console.log(user); // null in console
    if (user !== null
      && user.token !== null
      && user.token_deadline !== null
      && new Date(user.token_deadline) > new Date())
      return true;
    return false;
  }
}

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

CdkVirtualFor does not display any content

I'm facing an issue with implementing cdk-virtual-scroll in my chat application. Unfortunately, it's not showing anything on the screen. Strangely, when I resort to using the regular "ngFor", everything works smoothly. However, as soon as I switc ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...

Simulate an array within an Angular Component class

How can I simulate an array in Angular tests? myComponent.ts //variable declaration certificateArray: any[] = []; getCert(certName:any){ for (let index in this.certificateArray) { //perform some action } } myComponent.spec.ts it('should display def ...

I'm having trouble with Angular pipes in certain areas... but I must say, Stackblitz is truly incredible

Encountering this issue: ERROR in src\app\shopping-cart-summary\shopping-cart-summary.component.html(15,42): : Property '$' does not exist on type 'ShoppingCartSummaryComponent'. The error disappears when I remove the c ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Issue with RxDB: Collection not found upon reload

Exploring the integration of RxDB in my Angular project. I wanted to start with a simple example: export const LANG = { version: 0, title: "Language Key", type: "object", properties: { key: { type: "string", primary: true } }, requ ...

Do I have to utilize npm packages?

As a newcomer to Node.js, I'm diving into the world of node features while working on an Angular 2 project. One thing I've noticed is that every plugin seems to be imported from the node_modules folder. This has me wondering - is it absolutely n ...

Import JSON data into Angular 2 Component

After much effort, I have finally figured out how to load JSON data into an Angular 2 Component. datoer.service.ts: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

"In TypeScript, when something is undefined, it means its value

I am currently working on a class with code to help manage a database. export class DatabaseHelper { public browserID : number; private ConfigID = 17; } Within this class, I am attempting to access the value of ConfigID SetBrowserID() { ...

JavaScript: XHR struggles with managing multiple asynchronous requests

Hey there, I'm currently attempting to access a single resource multiple times with various parameters. Here's what I have so far: Essentially, I am making requests for the following domains: var domains = [ 'host1', 'host2&apos ...

What is the best way to arrange an array in either javascript or typescript based on a specific key, and in the case of identical keys,

Below is an array with objects that need to be sorted: [ { "Books": [], "_id": "5dea9a11a8e1bf301c462ce4", "FileName": "AAAAA", "Order": 99999 }, { "_id": "5dea9864a8e1bf301c462cdb", "Books": [], "FileName": "some1", ...

The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once ...

Angular 2 - Error: Regular expression missing forward slash syntax

Recently, I began working on an Angular 2 tutorial app using this repository. While I can successfully launch the app and display static content, I am facing challenges with rendering dynamic content from the component. I have a feeling that the error migh ...

Can you please explain the significance of classes <T> and <U> in Angular 2?

After diving into the Angular 2 TypeScript documentation, I have come across these two classes frequently. Can someone provide a detailed explanation of what they are? One example code snippet from the QueryList API documentation showcases: class QueryLi ...

'Watch for status within resolver's state (ngrx)'

Currently, I am using a resolver that calls a standard service and returns an Observable: return this.someService.getData() .map(data=> data.json()) I am looking to replace this setup with ngrx effects and store. In the resolver, I want to dispa ...

What is the best way to determine if the current page in Ionic 2 is being loaded from the sidemenu?

In my Ionic 2 application, there is a page that can be accessed either by clicking on a link in the sidenav or being active by default when the app is loaded. However, I want to implement an additional feature only when the page is accessed through the sid ...

Having too many node modules installed through npm in an Angular 2 quickstart project

Node/NPM versions: node: v5.4.0, npm: 3.3.12 I've embarked on the journey to learn Angular2 by diligently following the quick start tutorial on the official angular2 website. Angular2 Quickstart My package.json file mirrors that of the tutorial to ...

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...