Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 当用户未登录到Ionic 4时,如何从Id定义的路由重定向用户_Angular_Ionic Framework_Ionic4 - Fatal编程技术网

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

Angular 当用户未登录到Ionic 4时,如何从Id定义的路由重定向用户,angular,ionic-framework,ionic4,Angular,Ionic Framework,Ionic4,我在我的Ionic 4应用程序中工作,我在我的登录/注册系统中工作。我已经用id定义了路由,当用户未登录并尝试访问该路由时,它将重定向到登录页面,当用户登录时,他可以访问该路由,但问题是,当用户尝试使用id访问该路由时,它显示错误 这是我的标签.router.module.ts: import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { Ta

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

这是我的标签.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 {}
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();
  }
}
在此
选项卡中,选项卡2
带有id

这是我的身份验证.guard.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 {}
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();
  }
}
从'@angular/core'导入{Injectable};
从'@angular/router'导入{CanActivate,ActivatedRouteSnapshot,RouterStateSnashot};
从“rxjs”导入{Observable};
从'@ionic/Storage'导入{Storage};
从'@angular/Router'导入{Router};
从'@ionic/angular'导入{AlertController};
@注射的({
providedIn:'根'
})
导出类AuthenticationGuard实现CanActivate{
构造函数(专用路由器:路由器,专用存储:存储,公共alertController:alertController){}
激活(
下一步:ActivatedRouteSnapshot,
状态:RouterStateSnashot):可观察的|承诺|布尔值{
设isLoggedIn=false;
this.storage.get('ID')。然后((val)=>{
if(val){
isLoggedIn=真;
返回true;
}否则{
this.presentAlertConfirm();
返回false;
}
});
返回true;
}
异步presentAlertConfirm(){
const alert=等待this.alertController.create({
消息:“请登录参加挑战”,
按钮:[
{
文本:“取消”,
角色:“取消”,
cssClass:“次要”,
处理程序:()=>{
this.router.navigate(['/tabs/tab4']);
}
}]
});
等待警报。当前();
}
}
在guard中,当用户未登录时,它将重定向到登录页面

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


非常感谢您的帮助。

请尝试在您的授权保护上解决承诺。我的猜测是,现在您选择返回一个布尔值,但您使用的存储服务需要承诺,因此您不会等待承诺链完成执行

@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();
  }
}
@Injectable()
导出类AuthGuard实现了CanActivate{
建造师(
专用路由器:路由器,
) {}
激活(
路由:ActivatedRouteSnapshot,
状态:RouterStateSnapshot
):Promise | boolean{
返回新承诺((解决、拒绝)=>{
返回此.storage.get('ID')。然后((val)=>{
if(val){
isLoggedIn=真;
解析(真)
}否则{
this.presentAlertConfirm();
}
})
}
异步presentAlertConfirm(){
const alert=等待this.alertController.create({
消息:“请登录参加挑战”,
按钮:[
{
文本:“取消”,
角色:“取消”,
cssClass:“次要”,
处理程序:()=>{
解析(真)
this.router.navigate(['/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 {
        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();
  }
}
@Injectable()
导出类AuthGuard实现了CanActivate{
建造师(
专用路由器:路由器,
) {}
激活(
路由:ActivatedRouteSnapshot,
状态:RouterStateSnapshot
):Promise | boolean{
返回新承诺((解决、拒绝)=>{
返回此.storage.get('ID')。然后((val)=>{
if(val){
isLoggedIn=真;
解析(真)
}否则{
this.presentAlertConfirm();
}
})
}
异步presentAlertConfirm(){
const alert=等待this.alertController.create({
消息:“请登录参加挑战”,
按钮:[
{
文本:“取消”,
角色:“取消”,
cssClass:“次要”,
处理程序:()=>{
解析(真)
this.router.navigate(['/tabs/tab4']);
}
}]
});
等待警报。当前();
}
}

如果您想在出错后重定向,您应该移动
此.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();
  }
}
@Injectable()
导出类AuthGuard实现了CanActivate{
建造师(
专用路由器:路由器,
) {}
激活(
路由:ActivatedRouteSnapshot,
状态:RouterStateSnapshot
):Promise | boolean{
返回新承诺((解决、拒绝)=>{
返回此.storage.get('ID')。然后((val)=>{
if(val){
isLoggedIn=真;
解析(真)
}否则{
//将重定向放在此处:
this.router.navigate(['/tabs/tab4']);
this.presentAlertConfirm();
决议(假);
}
})
}
异步presentAlertConfirm(){
const alert=等待this.alertController.create({
消息:“请登录参加挑战”,
按钮:[
{
文本:“取消”,
角色:“取消”,
cssClass:“次要”,
处理程序:()=>{
解析(真)
}
}]
});
等待警报。当前();
}
}

如果您想在出错后重定向,您应该移动
此.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();
  }
}
@Injectable()
导出类AuthGuard实现了CanActivate{
建造师(
专用路由器:路由器,
) {}
激活(
路由:ActivatedRouteSnapshot,
状态:RouterStateSnapshot
):承诺| b