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