我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
角8。检查当前路由是否为基路由。
baseroute: boolean;
constructor(
private router: Router,
) {
router.events.subscribe((val: any) => {
if (val.url == "/") {
this.baseroute = true;
} else {
this.baseroute = false;
}
});
}
其他回答
对于Angular 7,应该这样写:
this.router.events。订阅((事件:事件)=> {})
具体示例如下:
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// Show loading indicator
}
if (event instanceof NavigationEnd) {
// Hide loading indicator
}
if (event instanceof NavigationError) {
// Hide loading indicator
// Present error to user
console.log(event.error);
}
});
}
}
如果你试图访问当前路由,同时监听路由变化:
router.events.pipe(filter(r=>r instanceof NavigationEnd)).subscribe(r=>{
console.log((r as NavigationEnd).url);
});
在Angular 2中,你可以订阅(Rx事件)一个Router实例。 你可以这样做
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
编辑(从rc.1开始)
class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
编辑2(从2.0.0开始)
请参见:路由器。活动文档
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
为那些使用Angular9+的人更新了答案,通过使用@angular/ Router提供的路由器API并监听路由变化
import { Component } from '@angular/core';
import { Router,NavigationEnd } from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Get Current Url Route Demo';
currentRoute: string;
routeSubscription: subscription;
constructor(private router: Router){
console.log(router.url);
this.routeSubscription = router.events.filter(event => event instanceof NavigationEnd)
.subscribe(event =>
{
this.currentRoute = event.url;
console.log(event);
});
}
}
在花了一些时间寻找解决方案后,我找到了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