当用户未登录时如何从用 Id 定义的路由重定向用户在 Ionic 4

How to redirect the user from the route defined with Id when the user is not login In Ionic 4

我在我的 Ionic 4 应用程序中工作,我在我的 login/register 系统中工作。我已经用 id 定义了路由,当用户未登录并尝试访问该路由时,它将重定向到登录页面,当用户登录时,他可以访问该路由,但问题是当用户正在尝试使用id访问该路由,它显示错误。

这是我的tabs.router.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';
import { AuthenticationGuard } from '../guards/authentication.guard';

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'tab1',
        children: [
          {
            path: '',
            loadChildren: '../tab1/tab1.module#Tab1PageModule'
          }
        ]
      },
      {
        path: 'tab2/:id',
        canActivate: [AuthenticationGuard],
        children: [
          {
            path: '',
            loadChildren: '../tab2/tab2.module#Tab2PageModule'
          }
        ]
      },
      {
        path: 'tab4',
        children: [
          {
            path: '',
            loadChildren: '../login/login.module#LoginPageModule'
          }
        ]
      },
      {
        path: 'tab3',
        children: [
          {
            path: '',
            loadChildren: '../tab3/tab3.module#Tab3PageModule'
          }
        ]
      },
      {
        path: '',
        redirectTo: '/tabs/tab1',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: '',
    redirectTo: '/tabs/tab1',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})
export class TabsPageRoutingModule {}

在这个tab2是带id的

这是我的authentication.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { Storage } from '@ionic/storage';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
@Injectable({
  providedIn: 'root'
})
export class AuthenticationGuard implements CanActivate {
  constructor(private router: Router, private storage: Storage, public alertController: AlertController) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    let isLoggedIn = false;
    this.storage.get('ID').then((val) => {
      if (val) {
        isLoggedIn = true;
        return true;
      } else {
        this.presentAlertConfirm();
        return false;
      }
    });
    return true;
  }

  async presentAlertConfirm() {
    const alert = await this.alertController.create({
      message: 'Please Login To Participate In The Challenge',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            this.router.navigate(['/tabs/tab4']);
          }
        }]
    });
    await alert.present();
  }
}

在守卫中,当用户未登录时,会重定向到登录页面。

但问题是当我尝试访问 tab2 页面时,它显示错误。

非常感谢任何帮助。

尝试解析你的 auth guard 上的 Promise。我的猜测是,现在您选择 return 一个布尔值,但您使用的是需要承诺的存储服务,因此您不会等待承诺链完成执行。

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private _router: Router,
  ) {}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> | boolean {
    return new Promise((resolve, reject) => {
    return this.storage.get('ID').then((val) => {
      if (val) {
        isLoggedIn = true;
        resolve(true)
      } else {
        this.presentAlertConfirm();
      }
    })
  }

async presentAlertConfirm() {
    const alert = await this.alertController.create({
      message: 'Please Login To Participate In The Challenge',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            resolve(true)
            this.router.navigate(['/tabs/tab4']);
          }
        }]
    });
    await alert.present();
  }
}

如果您想在错误后重定向,您应该将 this.router.navigate(['/tabs/tab4']); 移动到 AuthGuard。当前您在“取消”按钮单击句柄中导航到 /tabs/tab4

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private _router: Router,
  ) {}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> | boolean {
    return new Promise((resolve, reject) => {
    return this.storage.get('ID').then((val) => {
      if (val) {
        isLoggedIn = true;
        resolve(true)
      } else {
        // Place your redirect here:
        this.router.navigate(['/tabs/tab4']);
        this.presentAlertConfirm();
        resolve(false);
      }
    })
  }

async presentAlertConfirm() {
    const alert = await this.alertController.create({
      message: 'Please Login To Participate In The Challenge',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            resolve(true)
          }
        }]
    });
    await alert.present();
  }
}