我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
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);
});
}
其他回答
可以使用以下方法检测路由变化:
import {Router, ActivatedRoute} from '@angular/ Router '; 构造函数(私有路由:ActivatedRoute) {} This.router.events.subscribe ((event) => { 如果(事件){ / /做某事 } });
我会这样写:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
路由器3.0.0-beta。2应该是
this.router.events.subscribe(path => {
console.log('path = ', path);
});
角8。检查当前路由是否为基路由。
baseroute: boolean;
constructor(
private router: Router,
) {
router.events.subscribe((val: any) => {
if (val.url == "/") {
this.baseroute = true;
} else {
this.baseroute = false;
}
});
}
如果您只是想检查路由/查询参数更改,如localhost:4200/users/1?编辑=1到localhost:4200/users/2?Edit =0你可以像下面这样使用可观察的参数。
import { ActivatedRoute, Params } from '@angular/router';
export class SomeClass implements OnInit {
paramFromRoute;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.paramFromRoute = this.route.snapshot.params['paramName']; // this one is required for getting it first time
this.route.params.subscribe((params:Params)=>{
this.paramFromRoute = params['paramName'] // whenever route is changed, this function will triggered.
});
// for queryParams you can subscribe to this.route.queryParams
}
}