【问题标题】:Redirect the user when the user visits the particular route in Ionic 4当用户访问 Ionic 4 中的特定路线时重定向用户
【发布时间】:2025-10-09 09:10:01
【问题描述】:

我正在使用我的 Ionic 4 应用程序,我正在使用登录系统,当用户登录时,它将重定向到用户可以检查用户挑战的页面以及用户未登录时的页面,如果它尝试访问该页面,然后它应该重定向到另一个页面。

这是我的userlogin.ts

async UserLoginDetails($soctype, $socid) {
    const loading = await this.loadingController.create({
      message: 'Please Wait',
      duration: 1100,
      translucent: true,
    });
    await loading.present();
    const userdetailslogin = {
      email: this.userlogindet.value.email,
      password: this.userlogindet.value.password,
      social_type: $soctype,
      social_id: $socid,
    };
    this.chakapi.loginUser(userdetailslogin, 'userLogin').subscribe((data) => {
      console.log(data);
      if (data) {
        this.responseEdit = data;
        if (this.responseEdit.status === 'success') {
          console.log(this.responseEdit.data.id);
          this.storage.set('ID', this.responseEdit.data.id);
          this.presentAlertConfirm('Login Successful', 1);
        } else {
          this.presentAlertConfirm('Either You are not registered Or not approved user.', 0);
        }
      }
    });
    return await loading.onDidDismiss();
}

async presentAlertConfirm($messge, $para) {
    const alert = await this.alertController.create({
      message: $messge,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            // console.log('Confirm Cancel: blah');
            if ($para === 1) {
              this.modalController.dismiss();
              this.router.navigate(['/tabs/tab2']);
            }
          }
        }]
    });
    await alert.present();
}

当用户登录时,其用户 ID 将存储在存储中。

这是我的tabs.router.module.ts

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

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'tab1',
        children: [
          {
            path: '',
            loadChildren: '../tab1/tab1.module#Tab1PageModule'
          }
        ]
      },
      {
        path: 'tab2',
        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 存储在存储中,因为我想多次使用它。

非常感谢任何建议或帮助。请帮我写代码,因为我正在做一个项目,我想按时完成它。

非常感谢任何帮助。

【问题讨论】:

    标签: angular ionic-framework routing ionic4


    【解决方案1】:

    您可以使用警卫来完成此操作。守卫将确定用户是否登录。如果没有,用户将被重定向到另一条路线(登录页面或您希望他们登陆的任何地方)。


    authentication.guard.ts

    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationGuard implements CanActivate {
    
      constructor(private _router: Router) {}
    
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    
        let isLoggedIn: boolean = false;
    
        // NOTE: Do your logic here to determine if the user is logged in or not.
    
        // return true if use is authenticated
        if(isLoggedIn) return true;
    
        // else redirect the user to another route and return false.
        this._router.navigate(['login']);
        return false;
      }
    }
    

    tabs.router.module.ts

    const routes: Routes = [
      {
        path: 'tabs',
        component: TabsPage,
        children: [
          ...
          {
            path: 'tab2',
            canActivate: [AuthenticationGuard],
            children: [
              {
                path: '',
                loadChildren: '../tab2/tab2.module#Tab2PageModule'
              }
            ]
          },
          ...
        ]
      }
      ...
    ];
    

    Angular 防护就像过滤器一样使用。您可以向您的路由添加一组防护/过滤器,所有这些都必须满足才能访问该路由(充当链)。在您的路由数组中,将 canActivate 属性添加到您要过滤的路由。在上面的示例中,我将AuthenticationGuard 添加到tab2 路由中,该路由仅在用户尝试访问tab2 或其任何子节点时运行。您可以将 canActivate 放在路由的根 (tabs) 以过滤 tabs 路由的所有子节点(将过滤 tab1tab2 等)。

    https://angular.io/api/router/CanActivate

    https://angular.io/guide/router

    【讨论】:

    • 我将用户 ID 存储在存储中。你能帮我处理 authentication.guard.ts 中的代码吗?如果存储存在,则路由将打开,否则用户将重定向到其他路由。
    • @Rahul ,在守卫中,您只需通过设置的密钥将用户从存储中拉出。如果不是 nullundefined 则返回 true 。你可以说类似if(this.storage.get('user')) return true。如果this.storage 指的是服务,则必须将服务注入警卫的构造函数中。
    • 如果我在路径中定义id怎么办:'tab2/:id'。
    • 我不确定我是否理解您的问题。如果tab2/:idtab2 的子路由并且您将守卫放置在tab2 上,则导航到tab2:id 将需要守卫通过。
    • tab2/:id 会在 id 存在时打开,如果 id 不存在,它会重定向到其他路由。