我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
@Ludohen的回答很好,但如果你不想使用instanceof,请使用下面的方法
this.router.events.subscribe(event => {
if(event.constructor.name === "NavigationStart") {
// do something...
}
});
通过这种方式,您可以检查当前事件名称作为字符串,如果事件发生,您可以执行您计划的函数要执行的操作。
其他回答
更清晰的方法是继承RouteAware并实现onNavigationEnd()方法。
它是一个名为@bespunky/angular-zen的库的一部分。
NPM install @bespunky/angular-zen 让你的AppComponent扩展RouteAware并添加一个onNavigationEnd()方法。
import { Component } from '@angular/core';
import { NavigationEnd } from '@angular/router';
import { RouteAware } from '@bespunky/angular-zen/router-x';
@Component({
selector : 'app-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent extends RouteAware
{
protected onNavigationEnd(event: NavigationEnd): void
{
// Handle authentication...
}
}
RouteAware还有其他好处,比如: ✨任何路由器事件都可以有处理程序方法(Angular支持的路由器事件)。 ✨使用这个。路由器访问路由器 ✨使用这个。访问激活路由的路由 ✨使用this.componentBus访问RouterOutletComponentBus服务
Angular 7,如果你想订阅路由器
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
constructor(
private router: Router
) {
router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
console.log(event.url);
});
}
角4。X及以上:
这可以通过使用ActivatedRoute类的url属性来实现,如下所示:
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
注意: 你需要从angular/router包中导入和注入提供商
import { ActivatedRoute } from '@angular/router`
and
constructor(private activatedRoute : ActivatedRoute){ }
@Ludohen的回答很好,但如果你不想使用instanceof,请使用下面的方法
this.router.events.subscribe(event => {
if(event.constructor.name === "NavigationStart") {
// do something...
}
});
通过这种方式,您可以检查当前事件名称作为字符串,如果事件发生,您可以执行您计划的函数要执行的操作。
这里的答案是正确的路由器弃用。对于最新版本的路由器:
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
});