Home > Mobile >  How to call an async method in canActivate | Ionic ,Angular
How to call an async method in canActivate | Ionic ,Angular

Time:04-27

I want to get a token to authenticate the users. I save the data with import { Storage } from '@ionic/storage-angular'; the problem is that Storage methods just works in async mode.

This is the storage service

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);
  }

I initialize the database calling the method init() in ngOnInit AppComponent

This is the Guard

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;
    }
  }

}

CodePudding user response:

Change your function like so:

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

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

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