Loading

Ionic 在 AuthGuard 中验证登录状态

Ionic 在 AuthGuard 中验证登录状态

通过 ionic g service services/storage​ 创建 StorageService​ 管理存储相关的操作:

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) {
    this.init();
  }

  async init() {
    // If using, define drivers here: await this.storage.defineDriver(/*...*/);
    const storage = await this.storage.create();
    this._storage = storage;
  }

  // Create and expose methods that users of this service can
  // call, for example:
  public set(key: string, value: any) {
    this._storage?.set(key, value);
  }

  public checkLoginStatus(): Promise<any> {
    return new Promise((resolve) => {
        this.storage.get('token').then(result => {
            if (result) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    });
  }
}

通过 ionic g guard guards/auth​ 生成 guard​ 文件:

import { CanActivateFn, Router } from '@angular/router';
import { StorageService } from '../services/storage.service';
import { inject } from '@angular/core';

export const authGuard: CanActivateFn = async (route, state) => {
    const router = inject(Router);
    const storage = inject(StorageService);
    const loginStatus = await storage.checkLoginStatus();
    if (!loginStatus) {
        router.navigate(['/login']);
    }
    return loginStatus;
};

需要验证登录状态的路由中添加 canActivate: [authGuard]​:

const routes: Routes = [
  {
    path: '',
    canActivate: [authGuard],
    loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
  },
  {
    path: 'login',
    loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
  }
];

参考文章:

Ionic 存储

ionic-storage

posted @ 2024-05-17 09:32  zhpj  阅读(29)  评论(0)    收藏  举报