当用户未登录时,如何从使用Id定义的路由中重定向用户在Ionic 4中 [英] How to redirect the user from the route defined with Id when the user is not login In Ionic 4

查看:88
本文介绍了当用户未登录时,如何从使用Id定义的路由中重定向用户在Ionic 4中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working in my Ionic 4 app and I am working in my login/register system. I have defined the route with the id and when the user is not login and try to visit that route, it will redirect to login page and when the user is login then he can visit that route but the problem is that when the user is trying to visit that route with the id, it is showing the error.

这是我的 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();
  }
}

在守护程序中,当用户未登录时,它将重定向到登录页面.

In the guard, when the user is not login, it will redirect to the login page.

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

But the problem is when I try to visit the tab2 page, it is showing the error.

非常感谢您的帮助.

推荐答案

如果要在发生错误后进行重定向,则应将this.router.navigate(['/tabs/tab4']);移至AuthGuard.当前,您在取消"按钮单击手柄中导航到/tabs/tab4.

You should move this.router.navigate(['/tabs/tab4']); to AuthGuard if you want to redirect after error. Currently you navigate to /tabs/tab4 in Cancel button click handle.

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

这篇关于当用户未登录时,如何从使用Id定义的路由中重定向用户在Ionic 4中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆