我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
角4。X及以上:
这可以通过使用ActivatedRoute类的url属性来实现,如下所示:
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
注意: 你需要从angular/router包中导入和注入提供商
import { ActivatedRoute } from '@angular/router`
and
constructor(private activatedRoute : ActivatedRoute){ }
其他回答
我是这么说的:
class ClassName {
constructor(private router: Router) {
router.events.subscribe((value) => {
// see this
console.log(value instanceof NavigationEnd)
});
}
}
我会这样写:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
为那些使用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);
});
}
}
如果你试图访问当前路由,同时监听路由变化:
router.events.pipe(filter(r=>r instanceof NavigationEnd)).subscribe(r=>{
console.log((r as NavigationEnd).url);
});
简单的答案 角8。*
constructor(private route:ActivatedRoute) {
console.log(route);
}