我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
只需在AppRoutingModule上进行更改
@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
exports: [RouterModule]
})
其他回答
我从RC 5开始这样做
this.router.events
.map( event => event instanceof NavigationStart )
.subscribe( () => {
// TODO
} );
在组件中,你可能想尝试这样做:
import {NavigationEnd, NavigationStart, Router} from '@angular/router';
constructor(private router: Router) {
router.events.subscribe(
(event) => {
if (event instanceof NavigationStart)
// start loading pages
if (event instanceof NavigationEnd) {
// end of loading paegs
}
});
}
我正在使用angular5应用程序,我也面临着同样的问题。当我翻阅Angular文档时,它们提供了处理路由器事件的最佳解决方案。查看以下文档。
Angular中的路由器事件 在angar5中路由事件 但对于特定的情况,我们需要NavigationEnd事件 导航结束事件
表示导航成功结束时触发的事件
如何使用这个?
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRouteSnapshot, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit(): void {
//calls this method when navigation ends
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
//calls this stuff when navigation ends
console.log("Event generated");
}
});
}
}
什么时候用这个?
在我的情况下,我的应用程序共享公共仪表板的所有用户,如用户,管理员,但我需要显示和隐藏一些导航栏选项为每个用户类型。
这就是为什么每当url更改时,我需要调用返回登录用户信息的服务方法,根据响应,我将进行进一步的操作。
角8。检查当前路由是否为基路由。
baseroute: boolean;
constructor(
private router: Router,
) {
router.events.subscribe((val: any) => {
if (val.url == "/") {
this.baseroute = true;
} else {
this.baseroute = false;
}
});
}
位置的作品……
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);
}
}