在Angular中,可以使用ActivatedRoute
和Router
来订阅路由的激活状态。下面是一个示例代码,演示如何订阅两个级别的激活路由:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { takeUntil, filter } from 'rxjs/operators';
import { Subject } from 'rxjs';
OnInit
和OnDestroy
接口:@Component({
selector: 'app-my-component',
template: `
`,
})
export class MyComponent implements OnInit, OnDestroy {
private ngUnsubscribe = new Subject(); // 用于取消订阅的Subject
constructor(private route: ActivatedRoute, private router: Router) {}
ngOnInit() {
// 订阅路由参数的变化
this.route.params.pipe(takeUntil(this.ngUnsubscribe)).subscribe(params => {
// 在这里处理路由参数的变化
console.log('Route params changed', params);
});
// 订阅路由的激活状态变化
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
takeUntil(this.ngUnsubscribe)
)
.subscribe(() => {
// 在这里处理路由的激活状态变化
console.log('Route activated');
});
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
在上面的代码中,我们创建了一个ngUnsubscribe
的Subject
,用于取消订阅。然后在ngOnInit
中,我们订阅了route.params
来监听路由参数的变化,并在回调函数中处理这些变化。同时,我们还订阅了router.events
来监听路由的激活状态变化,并在回调函数中处理这些变化。最后,在ngOnDestroy
中,我们取消了所有的订阅。
请注意,为了只在路由导航结束后处理激活状态的变化,我们使用了filter
操作符来过滤出NavigationEnd
事件。这样可以确保我们只处理完成导航的事件。
希望以上解决方案对你有帮助!