Step-by-step guide on invoking an asynchronous method in canActivate for Ionic and Angular

My objective is to acquire a token for authenticating users. I am utilizing the

import { Storage } from '@ionic/storage-angular';
to store the data, but I am encountering an issue where the Storage methods only function in asynchronous mode.

Here is the storage service implementation:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage-angular';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
  }

  public async init() {
    const storage = await this.storage.create();
    this._storage = storage;
  }


  public async set(key: string, value: any): Promise<void> {
    const data = await this._storage?.set(key, value);
  }

  public async get(key: string): Promise<any> {
    return data await this._storage?.get(key);
  }

  public async remove(key: string): Promise<void> {
    await this._storage?.remove(key);
  }

To initialize the database, I invoke the init() method in the ngOnInit lifecycle hook of the AppComponent.

Next, here is the implementation of the UserGuard:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { StorageService } from '../services/storage.service';

@Injectable({
  providedIn: 'root'
})
export class UserGuard implements CanActivate {

  constructor(
    private router: Router,
    private storage: StorageService
  ) {}


  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> {

    const data = this.storage.get('token');

    if (!data) {
      this.router.navigateByUrl('/login');
    }
    else {
      return true;
    }
  }

}

Answer №1

Revise your code in the following manner:

  async authenticateUserAccess(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Promise<boolean> {

    const userToken = await this.storage.get('token');

    if (!userToken) {
      this.router.navigateByUrl('/login');
      return false;
    }
    else {
      return true;
    }
  }

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

Creating a component with @input for unit tests in Angular can be achieved through the following steps

I'm encountering issues while attempting to create a testing component with an @input. The component utilizes properties from the feedback model, and although I imported them into the test file, errors are being displayed. Can anyone offer assistance? ...

Tips for sending information back to the previous screen in React Native Navigation version 5

Recently, I upgraded to react native navigation version 5 and now I am facing an issue with sending data back to the previous screen when making a goBack() call. To navigate to the next view, I use: const onSelectCountry = item => { console.log(it ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

Having trouble with installing npm package from gitlab registry

I recently uploaded my npm package to the GitLab package registry. While the upload seemed successful, I am facing an issue trying to install the package in another project. When I run npm install, I encounter the following error: PS E:\faq\medu ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Prevent special characters in input fields using Angular and TypeScript

I am currently working on an Angular project using Ant Design ng Zorro. I've encountered an issue with validation when trying to restrict special characters in an input field. Despite setting up the validation rules, it seems that the key press event ...

Is there a way to remove trigger characters in vscode api completion function?

I am developing a vscode extension that requires custom completion for json files. I would like to know if it is possible to hide the trigger character when using autocompletions. Let me explain further : Imagine the trigger character is '.' In ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

What could be causing my Angular app to be unable to locate the embedded component?

This particular component is called HomeTabComponent and it is embedded here. @Component({ selector: 'app-home-tab', templateUrl: './home-tab.component.html', styleUrls: ['./home-tab.component.scss'] }) export class Ho ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

Failure to Execute Angular HttpClient Request

I'm facing an issue with firing the HttpClient request. It seems like there might be a problem with importing or providing, but I can't pinpoint where it is exactly. The API works fine, but the call never goes through. Here are the environment/v ...

Struggling to integrate Docker compatibility into an established NextJS project, encountering the frustrating "stat app/.next/standalone: file does not exist" message

I'm currently in the process of enhancing my existing NextJS + TypeScript project with Docker support and preparing to deploy it on Google Cloud Run. To achieve this, I've been referring to a helpful guide available at: https://github.com/vercel/ ...

Steps for changing tabs in Ionic depending on a specific condition

I have a mobile app built with the Ionic Framework that features 4 tabs, but I want to limit the visibility of only three tabs at a time. The first two tabs (Tab1 and Tab2) are always visible. However, the third tab should display either Tab 3a or Tab 3b ...

Having trouble making API calls in an Angular application

When attempting to call the api using the httpClient method, I encountered an issue where the result was returning as undefined. Below is the code from the services file. contact-service.services.ts import { Injectable } from '@angular/core'; ...

What is the reason for `downlevelIteration` not being enabled by default?

When directing towards ES5 and using the spread operator ... to convert an Iterator to an Array, it prompts the need for the -downlevelIteration compiler option. Enabling this option allows the spread operators to function without any errors. I'm cur ...

Press the text in a React Native TypeScript component to trigger a render

I am a newcomer to React Native and TypeScript, and I am struggling to figure out how to display something on the page of my app after a button is pressed. Below is the function I'm using: const getRandomNumber = () ={ const number = Math.fl ...

Expansive Carousel Feature with Ng Bootstrap

In my Angular 5 application, I am utilizing the Carousel component from "@ng-bootstrap/ng-bootstrap": "^1.1.2". I am trying to display pictures in full screen but when I press F11, the image appears like this. I am unsure of which CSS properties to apply ...

Invoke the method in customButton component of fullcalendar

I've integrated a custom button into my fullcalendar: ngOnInit() { this.calendarOptions = { customButtons: { custom1: { text: 'Add event', click() { this.openModal(); } } }, height: 600, editable: t ...

Troubleshooting auxiliary routes in Angular: why won't they work

I am facing an issue where I am trying to load components into a router outlet nested within another component. Within my ProgramComponent (with the selector app-program), I have defined a router outlet. <a routerLink="admin1">One</a> <a ro ...

How can I incorporate multiple quality sources into a flowplayer using Angular?

Is there a way to add multiple sources with different qualities like 1080p, 720p etc.? Thank you in advance. flowplayer('#my_player', { src: '../assets/videos/video_1080p.mp4', // title: 'This is just demo&apo ...