不说废话直接上干货
在app-routing中:
import {AuthGuard} from './_guards/auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent,
canActivate: [AuthGuard],
children: [
xxx
xxx
xxx
]
},
];
下一步:配置 auth.guard
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router';
import { SessionService } from 'app/shared/session.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router,
private sessionService: SessionService,
) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const user = this.sessionService.getCurrentUser() ; //get login user msg
if (user&&user.id) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
if (state.url === '/') {
console.log('没有登陆,直接跳转登陆页');
this.router.navigate(['/login']);
} else {
console.log('没有登陆,访问子页面,直接跳转登陆页');
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
}
return false;
}
}
(不知道angular7是否可行,因为前段时间用了下ng7 发现内部http的封装已经改变了,国内外目前为止也没有针对ng7的详细文档)