非懒加载模式下,想要pages组件能够正常显示切换的路由和固定头部足部,路由只能像上述这样配置,也就是所有组件都在app模块中声明,显然不是很推荐这种模式,切换回懒加载模式:
{ path: '', canLoad: [AuthGuard], canActivate: [AuthGuard], canActivateChild: [ AuthGuard ], canDeactivate: [AuthGuard], loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) },
pages-routing.module.ts
初始模板:
const routes: Routes = [ { path: '', redirectTo: 'index', pathMatch: 'full' }, { path: 'index', component: IndexComponent, data: { title: '公司主页' } }, { path: 'about', component: AboutComponent, data: { title: '关于我们' } }, { path: 'contact', component: ContactComponent, data: { title: '联系我们' } }, { path: 'news', canDeactivate: [AuthGuard], loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule) }, ]
浏览器截图:
明明我们的html写了头部和底部组件却没显示?
路由的本质:根据配置的path路径去加载组件或者模块,此处我们是懒加载了路由,根据路由模块再去加载不同组件,唯独缺少了加载了pages组件,其实理解整个并不难,index.html中有个<app-root></app-root>,这就表明app组件被直接插入了dom中,反观pages组件,根本不存在直接插进dom的情况,所以这个组件根本没被加载,验证我们的猜想很简单:
export class PagesComponent implements OnInit { constructor() { } ngOnInit() { alert(); } }
经过刷新页面,alert()窗口并没有出现~,可想而知,直接通过路由模块去加载了对应组件;其实我们想要的效果就是之前改造前的app.component.html效果,所以路由配置要参照更改:
const routes: Routes = [ { path: '', component: PagesComponent, children: [ { path: '', redirectTo: 'index', pathMatch: 'full' }, { path: 'index', component: IndexComponent, data: { title: '公司主页' } }, { path: 'about', component: AboutComponent, data: { title: '关于我们' } }, { path: 'contact', component: ContactComponent, data: { title: '联系我们' } }, { path: 'news', canDeactivate: [AuthGuard], loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule) }, ] } ];
这样写,pages组件就被加载了,重回正题,差点回不来,我们在登录组件中写了简单的登录逻辑:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; constructor( private fb: FormBuilder, private router: Router ) { } ngOnInit() { this.loginForm = this.fb.group({ loginName: ['', [Validators.required]], password: ['', [Validators.required]] }); console.log(this.loginForm); } loginSubmit(event, value) { if (this.loginForm.valid) { window.localStorage.setItem('loginfo', JSON.stringify(this.loginForm.value)); this.router.navigateByUrl('index'); } } }
守卫中:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // 权限控制逻辑如 是否登录/拥有访问权限 console.log('canActivate', route); const isLogin = window.localStorage.getItem('loginfo') ? true : false; if (!isLogin) { console.log('login'); this.router.navigateByUrl('login'); } return true; }
路由离开(选定应用的组件是contact组件):