1 路由
1 监听路由的变化
1 导包
Subscription
订阅对象
Routrer
路由
ActivationEnd
属于路由变化时间中的一个阶段 表示:在路由的“解析”阶段的激活部分结束时触发的事件。
2 知识预备
构造方法:经常处理初始化和给属性赋值的动作construtor()
是在ngOnInit()
之前执行的。
3 关键点
1 this.router.events
路由的生命周期
2 pipe(filter(e => e instanceof ActivationEnd))
从路由众多个过程中过滤出ActivationEnd
这个阶段
3 subscribe(() => this.setActive())
当到达ActivationEnd
这个阶段后就执行setActive()
方法
this.router$ = this.router.events.pipe(filter(e => e instanceof ActivationEnd)).subscribe(() => this.setActive());
//引入订阅 路由
import { Subscription } from 'rxjs';
import { Router, ActivationEnd, ActivatedRoute } from '@angular/router';
export class MaterialManageComponent implements OnInit {
//初始化订阅对象
private router$: Subscription;
// subscribe监听路由的生命周期,当到了被监听的阶段,就执行subscribe中的方法setActive()。
constructor(private router: Router, private route: ActivatedRoute) {
this.router$ = this.router.events.pipe(filter(e => e instanceof ActivationEnd)).subscribe(() => this.setActive());
}
private setActive() {
let key = '';
console.log(`setAction:${this.router.url}`);
if (this.router.url.match(/manage\/(\S*)\?/) !== null) {
key = this.router.url.match(/manage\/(\S*)\?/)[1];
}
let url = this.router.url;
let paths = url.split('/');
key = paths[paths.length - 1];
let flag = true;
for (let index = 0; index < this.menus.length; index++) {
if (key === this.menus[index].key) {
this.menus[index].selected = this.menus[index].key === key;
flag = false;
}
if (index === this.menus.length - 1 && flag) {
this.menus[index].selected = this.menus[0].key === key;
}
}
if (this.menus.find(w => w.selected)) {
this.title = this.menus.find(w => w.selected).title;
}
}
}