我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
我正在使用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更改时,我需要调用返回登录用户信息的服务方法,根据响应,我将进行进一步的操作。
其他回答
对于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);
}
});
}
}
我从RC 5开始这样做
this.router.events
.map( event => event instanceof NavigationStart )
.subscribe( () => {
// TODO
} );
以上大多数解决方案是正确的,但我面临的问题是这个发射多次'导航发射'事件。当我改变任何路由时,此事件被触发。所以hear是Angular 6的完整解决方案。
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';
export class FooComponent implements OnInit, OnDestroy {
private _routerSub = Subscription.EMPTY;
constructor(private router: Router){}
ngOnInit(){
this._routerSub = this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe((value) => {
//do something with the value
});
}
ngOnDestroy(){
this._routerSub.unsubscribe();
}
}
简单的答案 角8。*
constructor(private route:ActivatedRoute) {
console.log(route);
}
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.showProgressBar = true
} else if (event instanceof NavigationEnd) {
this.showProgressBar = false
}
else if (event instanceof NavigationCancel) {
this.showProgressBar = false
}
})
您可以在任何事件路由状态下订阅