ionic4 入门 (四) 路由守卫
判断用户是否登录 , 在进入购物车和个人中心 界面的时候, 如果用户没有登录, 需要让用户先进入登录界面
创建守卫
-
cli ionic g guard guard/loginGuard 创建守卫
编写守卫规则
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { NavController } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class LoginGuardGuard implements CanActivate {
constructor(private nav: NavController) {
}
// tslint:disable-next-line:max-line-length
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
const token = window.localStorage.getItem('token');
if (token == null || token === undefined) {
this.nav.navigateForward('login');
return false;
}
return true;
}
}
注册路由
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LoginGuardGuard } from 'src/guard/login-guard.guard';
import { HttpClientModule } from '@angular/common/http';
import { HttpService } from './http/http.service';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
LoginGuardGuard, // 注册路由守卫
HttpService, // 网络请求的服务
],
bootstrap: [AppComponent]
})
export class AppModule {}
使用守卫
- 在 tabls.module.ts 界面,配置路由守卫
{
path: 'cart',
children: [
{
path: '',
loadChildren: '../cart/cart/cart.module#CartPageModule',
canActivate: [LoginGuardGuard]
}
]
},
{
path: 'mine',
children: [
{
path: '',
loadChildren: '../mine/mine/mine.module#MinePageModule',
canActivate: [LoginGuardGuard]
}
]
}
测试路由效果
如果不行 请留言