import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
@Injectable({providedIn: 'root'})
export class LoginGuard implements CanActivate {
constructor(
private router: Router
) {}
canActivate() {
// 这里判断登录状态, 返回 true 或 false
if(sessionStorage['isLogin']) {
return true;
}else {
this.router.navigate(['login']);
return false;
}
}
}
// 路由守卫,未登录跳转到登录页
import { LoginGuard } from './guard/login-guard.service';
const routes: Routes = [
{ path: '', redirectTo : 'login',pathMatch:'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [LoginGuard]},
{ path: 'personal', component: PersonalComponent, canActivate: [LoginGuard]},
{ path: 'account', component: AccountComponent, canActivate: [LoginGuard]},
{ path: 'product', component: ProductComponent, children:[
{ path: '', component : ProductDescComponent },
{ path: 'seller/:id', component : SellerInfoComponent }
] ,canActivate: [LoginGuard]},
{ path: '**', component: Code404Component }
];
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({providedIn: 'root'})
export class AuthGuard implements CanActivate {
constructor(
private router: Router
) {}
// 产品页面权限
private JViewProduct = localStorage['JViewProduct']?true:false;
// 账户页面权限
private JViewAccount = localStorage['JViewAccount']?true:false;
canActivate(
route: ActivatedRouteSnapshot
): boolean {
let isPass = true;
if(route.data&&route.data.target) {
switch (route.data.target) {
case 'product':
isPass = this.JViewProduct;
break;
case 'account':
isPass = this.JViewAccount;
break;
default:
break;
}
}
if(!isPass) {
// 如果路由无法访问
this.shouldToPath();
}
return isPass;
}
// 应该跳转到的路径
shouldToPath() {
his.router.navigate(['home']);
}
}
import { LoginGuard } from './guard/login-guard.service';
import { AuthGuard } from './guard/auth-guard.service';
const routes: Routes = [
{ path: '', redirectTo : 'login',pathMatch:'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [LoginGuard]},
{ path: 'personal', component: PersonalComponent, canActivate: [LoginGuard]},
{ path: 'account', component: AccountComponent, canActivate: [LoginGuard, AuthGuard]},
{ path: 'product', component: ProductComponent, children:[
{ path: '', component : ProductDescComponent },
{ path: 'seller/:id', component : SellerInfoComponent }
] ,canActivate: [LoginGuard, AuthGuard},
{ path: '**', component: Code404Component }
];
import { CanDeactivate } from "@angular/router";
import { ProductComponent } from "../product/product.component";
@Injectable({providedIn: 'root'})
export class UnsaveGuard implements CanDeactivate<ProductComponent>{
//第一个参数 范型类型的组件
//根据当前要保护组件 的状态 判断当前用户是否能够离开
canDeactivate(component: ProductComponent){
return window.confirm('你还没有保存,确定要离开吗?');
}
}
import { LoginGuard } from './guard/login-guard.service';
import { AuthGuard } from './guard/auth-guard.service';
import { UnsaveGuard } from './guard/unsave-guard.service';
const routes: Routes = [
{ path: '', redirectTo : 'login',pathMatch:'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [LoginGuard]},
{ path: 'personal', component: PersonalComponent, canActivate: [LoginGuard]},
{ path: 'account', component: AccountComponent, canActivate: [LoginGuard, AuthGuard]},
{ path: 'product', component: ProductComponent, children:[
{ path: '', component : ProductDescComponent },
{ path: 'seller/:id', component : SellerInfoComponent }
] ,canActivate: [LoginGuard, AuthGuard], canDeactivate: [UnsaveGuard]},
{ path: '**', component: Code404Component }
];
export class Product{
constructor(public id:number, public name:string){}
}
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Product } from "../product/product.component";
@Injectable({providedIn: 'root'})
export class ProductResolve implements Resolve<Product>{
constructor(private router: Router,private service: GetDataService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
let productId: number = route.params["id"];
if (productId) { // 假设id存在去请求服务器
return new Product(1, "iPhone7");// 或者 return this.service.getProduct(参数);
} else { // id不在
this.router.navigate(["/home"]);
return undefined;
}
}
}
import { LoginGuard } from './guard/login-guard.service';
import { AuthGuard } from './guard/auth-guard.service';
import { UnsaveGuard } from './guard/unsave-guard.service';
import { ProductResolve } from './guard/product-resolve.service';
const routes: Routes = [
{ path: '', redirectTo : 'home',pathMatch:'full' },
{ path: 'home', component: HomeComponent },
{ path: 'product/:id', component: ProductComponent, children:[
{ path: '', component : ProductDescComponent },
{ path: 'seller/:id', component : SellerInfoComponent }],
resolve: { //resolve是一个对象
product : ProductResolve //想传入product,product由ProductResolve生成
}},
{ path: '**', component: Code404Component }
];
export class AppRoutingModule { }
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
private productId: number;
private productName: string;
constructor(private routeInfo: ActivatedRoute) { }
ngOnInit() {
// this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]);
this.routeInfo.data.subscribe(
(data:{product:Product})=>{
this.productId=data.product.id;
this.productName=data.product.name;
}
);
}
}
export class Product{
constructor(public id:number, public name:string){
}
}
<div class="product">
<p>
这里是商品信息组件
</p>
<p>
商品id是: {{productId}}
</p>
<p>
商品名称是: {{productName}}
</p>
<a [routerLink]="['./']">商品描述</a>
<a [routerLink]="['./seller',99]">销售员信息</a>
<router-outlet></router-outlet>
</div>
点商品详情按钮,不传商品ID,是错误id,会直接跳转到主页。
注意点:
如果应用是小于angular 6 那么服务中
@Injectable({providedIn: 'root'})应该改为@Injectable()
在路由模块中就需要注入服务比如
@NgModule({
providers: [LoginGuard,AuthGuard,UnsaveGuard,ProductResolve]
})