我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
这里的答案是正确的路由器弃用。对于最新版本的路由器:
this.router.changes.forEach(() => {
// Do whatever in here
});
or
this.router.changes.subscribe(() => {
// Do whatever in here
});
要了解两者之间的区别,请查看这个SO问题。
Edit
对于最新的您必须做:
this.router.events.subscribe(event: Event => {
// Handle route change
});
其他回答
在Angular 8中,你应该这样做。router.events。订阅((事件:事件)=> {})
例子:
import { Component } from '@angular/core';
import { Router, Event } from '@angular/router';
import { NavigationStart, NavigationError, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
//Router subscriber
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
//do something on start activity
}
if (event instanceof NavigationError) {
// Handle error
console.error(event.error);
}
if (event instanceof NavigationEnd) {
//do something on end activity
}
});
}
}
我会这样写:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
在花了一些时间寻找解决方案后,我找到了Angular 13.1.1的两个更新的变通方案:
第一选择:
constructor(private router: Router) {
router.events.forEach((event) => {
if (event instanceof NavigationStart) {
// Your code
// Use (event.url) to get URL that is being navigated
}
});
}
第二个选项
routerSubscription:订阅| undefined; 构造函数(私有路由器:router) {} ngAfterViewInit(): void { 这一点。routerSubscription = this.router.events.subscribe((event) => { if(事件实例of NavigationEnd) { //你的代码 //使用(event.url)获取正在导航的URL } }); }
记得取消订阅销毁循环
ngOnDestroy(): void {
this.routerSubscription?.unsubscribe();
}
还要根据您的情况注意是否更好地使用
事件实例的NavigationStart
or
事件实例的NavigationEnd
如果你试图访问当前路由,同时监听路由变化:
router.events.pipe(filter(r=>r instanceof NavigationEnd)).subscribe(r=>{
console.log((r as NavigationEnd).url);
});
以上大多数解决方案是正确的,但我面临的问题是这个发射多次'导航发射'事件。当我改变任何路由时,此事件被触发。所以hear是Angular 6的完整解决方案。
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
export class FooComponent implements OnInit, OnDestroy {
private _routerSub = Subscription.EMPTY;
constructor(private router: Router){}
ngOnInit(){
this._routerSub = this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe((value) => {
//do something with the value
});
}
ngOnDestroy(){
this._routerSub.unsubscribe();
}
}