我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
位置的作品……
import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private location: Location) {
this.location.onUrlChange(x => this.urlChange(x));
}
ngOnInit(): void {}
urlChange(x) {
console.log(x);
}
}
其他回答
我是这么说的:
class ClassName {
constructor(private router: Router) {
router.events.subscribe((value) => {
// see this
console.log(value instanceof NavigationEnd)
});
}
}
@Ludohen的回答很好,但如果你不想使用instanceof,请使用下面的方法
this.router.events.subscribe(event => {
if(event.constructor.name === "NavigationStart") {
// do something...
}
});
通过这种方式,您可以检查当前事件名称作为字符串,如果事件发生,您可以执行您计划的函数要执行的操作。
角4。X及以上:
这可以通过使用ActivatedRoute类的url属性来实现,如下所示:
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
注意: 你需要从angular/router包中导入和注入提供商
import { ActivatedRoute } from '@angular/router`
and
constructor(private activatedRoute : ActivatedRoute){ }
角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);
}
});
}
}