我希望在我的 AppComponent
中检测路线变化。
此后,我将检查全局用户令牌以查看用户是否已登录,以便在用户未登录时重定向用户。
在 Angular 2 中,您可以 subscribe
(Rx 事件)到路由器实例。所以你可以做类似的事情
class MyClass {
constructor(private router: Router) {
router.subscribe((val) => /*whatever*/)
}
}
编辑(自 rc.1 起)
class MyClass {
constructor(private router: Router) {
router.changes.subscribe((val) => /*whatever*/)
}
}
编辑 2(从 2.0.0 开始)
class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
RxJS 6
router.events.pipe(filter(event => event instanceof NavigationStart))
感谢 Peilonrayz(请参阅下面的评论)
新路由器 >= RC.3
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router';
constructor(router:Router) {
router.events.forEach((event) => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
});
}
您还可以按给定事件过滤:
import 'rxjs/add/operator/filter';
constructor(router:Router) {
router.events
.filter(event => event instanceof NavigationStart)
.subscribe((event:NavigationStart) => {
// You only receive NavigationStart events
});
}
使用 pairwise
operator 获取上一个和当前事件也是一个好主意。 https://github.com/angular/angular/issues/11268#issuecomment-244601977
导入'rxjs/add/operator/pairwise';从'@angular/router'导入{路由器};导出类 AppComponent { 构造函数(私有路由器:路由器) { this.router.events.pairwise().subscribe((event) => { console.log(event); }); }; }
Argument of type '(event: Event) => void' is not assignable to parameter of type
上引发编译错误
Argument of type '(event: Event) => void' is not assignable to parameter of type
错误是因为在您的过滤器片段中您订阅的是 Event 类型的对象,而不是 NavigationEvent。
对于 Angular 7,有人应该这样写:
this.router.events.subscribe((event: Event) => {})
一个详细的例子可以如下:
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);
}
});
}
}
Angular 7,如果您想从 subscribe
到 router
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);
});
}
url
和 urlAfterRedirects
,在重定向的情况下,事件将 url
设置为进行路径重定向的位置,并将 urlAfterRedirects
设置为重定向后的路径
Angular 4.x 及更高版本:
这可以使用 ActivatedRoute 类的 url 属性来实现,如下所示,
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
注意:您需要从 angular/router
包中导入和注入提供程序
import { ActivatedRoute } from '@angular/router`
和
constructor(private activatedRoute : ActivatedRoute){ }
在 Angular 8 中,您应该像 this.router.events.subscribe((event: Event) => {})
例子:
import { Component } from '@angular/core';
import { Router, Event } from '@angular/router';
import { NavigationStart, NavigationError, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
//Router subscriber
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
//do something on start activity
}
if (event instanceof NavigationError) {
// Handle error
console.error(event.error);
}
if (event instanceof NavigationEnd) {
//do something on end activity
}
});
}
}
在角度 6 和 RxJS6 中:
import { filter, debounceTime } from 'rxjs/operators';
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
debounceTime(40000)
).subscribe(
x => {
console.log('val',x);
this.router.navigate(['/']); /*Redirect to Home*/
}
)
import {Router, NavigationEnd} from "@angular/router"
的导入
路由器 3.0.0-beta.2 应该是
this.router.events.subscribe(path => {
console.log('path = ', path);
});
在 Angular 10 中,您可以执行以下操作...
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-my-class',
templateUrl: './my-class.component.html',
styleUrls: ['./my-class.component.scss']
})
export class MyClassComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
// code goes here...
});
}
}
这里的答案对于 router-deprecated
是正确的。对于 router
的最新版本:
this.router.changes.forEach(() => {
// Do whatever in here
});
或者
this.router.changes.subscribe(() => {
// Do whatever in here
});
要查看两者之间的区别,请查看 this SO question。
编辑
对于最新的,您必须执行以下操作:
this.router.events.subscribe(event: Event => {
// Handle route change
});
router
已再次更新(我还没有更新我的答案),所以我不确定最新情况如何。对于我写的 router
,你不能。 @akn
在组件中,您可能想试试这个:
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
}
});
}
位置工作...
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);
}
}
通过以下方式捕获路线更改事件...
import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';
@Component({
selector: "my-app",
templateUrl: "app/app.component.html",
styleUrls: ["app/app.component.css"]
})
export class AppComponent {
constructor(private cacheComponentObj: CacheComponent,
private router: Router) {
/* Route event types
NavigationEnd
NavigationCancel
NavigationError
RoutesRecognized
*/
router.events.forEach((event: NavigationEvent) => {
//Before Navigation
if (event instanceof NavigationStart) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
//After Navigation
if (event instanceof NavigationEnd) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
});
}
}
如果您在收听路由更改时尝试访问当前路由:
router.events.pipe(filter(r=>r instanceof NavigationEnd)).subscribe(r=>{
console.log((r as NavigationEnd).url);
});
以上大多数解决方案都是正确的,但我面临多次发出“导航发出”事件的问题。当我更改任何路线时,会触发此事件。所以听到的是 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();
}
}
为使用 Angular9+ 的用户更新答案,通过使用 @angular/router
提供的 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);
});
}
}
我会写这样的东西:
ngOnInit() {
this.routed = this.router.events.map( event => event instanceof NavigationStart )
.subscribe(() => {
} );
}
ngOnDestroy() {
this.routed.unsubscribe();
}
@Ludohen 答案很好,但如果您不想使用 instanceof
,请使用以下
this.router.events.subscribe(event => {
if(event.constructor.name === "NavigationStart") {
// do something...
}
});
通过这种方式,您可以将当前事件名称作为字符串检查,如果事件发生,您可以执行您计划函数执行的操作。
instanceOf
,这样您的示例也可以在生产代码中工作。 if(event instanceOf NavigationStart) {
if(event instanceof NavigationStart)
在 Angular 7 中,我已经解决了使用以下函数在特定页面上启用和禁用导航栏的问题。
首先你应该导入 NavigationEnd
import { NavigationEnd, Router } from '@angular/router';
navbar.component.ts
public isNavbar=false;
ngAfterViewInit() {
// nabar enable / disable function
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
if(event.url.includes('dashboard')){
this.isNavbar=true;
}else{
this.isNavbar=false;
}
}
});
}
navbar.component.html
<mat-toolbar *ngIf="isNavbar" class="mat-elevation-z1 nav-tool-bar">
<button mat-button routerLink="/dashboard" routerLinkActive="active-list-item"><svg aria-hidden="true" focusable="false" data-prefix="fal" data-icon="paper-plane" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="nav-bar-icon svg-inline--fa fa-paper-plane fa-w-16"><path fill="currentColor" d="M464 4.3L16 262.7C-7 276-4.7 309.9 19.8 320L160 378v102c0 30.2 37.8 43.3 56.7 20.3l60.7-73.8 126.4 52.2c19.1 7.9 40.7-4.2 43.8-24.7l64-417.1C515.7 10.2 487-9 464 4.3zM192 480v-88.8l54.5 22.5L192 480zm224-30.9l-206.2-85.2 199.5-235.8c4.8-5.6-2.9-13.2-8.5-8.4L145.5 337.3 32 290.5 480 32l-64 417.1z" class=""></path></svg>
Campagnes</button>
<button mat-button routerLink="fake" routerLinkActive="active-list-item"><svg aria-hidden="true" focusable="false" data-prefix="fal" data-icon="box-open" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 608 512" class="nav-bar-icon svg-inline--fa fa-box-open fa-w-19"><path fill="currentColor" d="M606.4 143.8L557.5 41c-2.7-5.6-8.1-9-13.9-9C543 32 304 64 304 64S65 32 64.4 32c-5.8 0-11.2 3.5-13.9 9L1.6 143.8c-4.4 9.2.3 20.2 9.6 23l49.5 14.9V393c0 14.7 9.5 27.5 23 31l205.4 54.1c13 3.4 23.7 1.5 29.5 0L524.2 424c13.5-3.6 23-16.4 23-31V181.7l49.5-14.9c9.4-2.8 14-13.8 9.7-23zM73 65.3l180.9 24.3-57.1 99.8-159.9-48.1 36.1-76zm18.2 125.6C208.3 226.1 200.5 224 203.6 224c5.4 0 10.5-2.9 13.3-7.9l71.9-125.5V445L91.2 393V190.9zM516.8 393l-197.6 52V90.5L391.1 216c2.9 5 8 7.9 13.3 7.9 3.1 0-5 2.1 112.4-33.1V393zM411.3 189.3l-57.1-99.8L535 65.3l36.1 76-159.8 48z" class=""></path></svg>
Ressources</button>
<button mat-button routerLink="fake" routerLinkActive="active-list-item"><svg aria-hidden="true" focusable="false" data-prefix="fal" data-icon="life-ring" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="nav-bar-icon svg-inline--fa fa-life-ring fa-w-16"><path fill="currentColor" d="M256 8C119.033 8 8 119.033 8 256s111.033 248 248 248 248-111.033 248-248S392.967 8 256 8zm168.766 113.176l-62.885 62.885a128.711 128.711 0 0 0-33.941-33.941l62.885-62.885a217.323 217.323 0 0 1 33.941 33.941zM256 352c-52.935 0-96-43.065-96-96s43.065-96 96-96 96 43.065 96 96-43.065 96-96 96zM363.952 68.853l-66.14 66.14c-26.99-9.325-56.618-9.33-83.624 0l-66.139-66.14c66.716-38.524 149.23-38.499 215.903 0zM121.176 87.234l62.885 62.885a128.711 128.711 0 0 0-33.941 33.941l-62.885-62.885a217.323 217.323 0 0 1 33.941-33.941zm-52.323 60.814l66.139 66.14c-9.325 26.99-9.33 56.618 0 83.624l-66.139 66.14c-38.523-66.715-38.5-149.229 0-215.904zm18.381 242.776l62.885-62.885a128.711 128.711 0 0 0 33.941 33.941l-62.885 62.885a217.366 217.366 0 0 1-33.941-33.941zm60.814 52.323l66.139-66.14c26.99 9.325 56.618 9.33 83.624 0l66.14 66.14c-66.716 38.524-149.23 38.499-215.903 0zm242.776-18.381l-62.885-62.885a128.711 128.711 0 0 0 33.941-33.941l62.885 62.885a217.323 217.323 0 0 1-33.941 33.941zm52.323-60.814l-66.14-66.14c9.325-26.99 9.33-56.618 0-83.624l66.14-66.14c38.523 66.715 38.5 149.229 0 215.904z" class=""></path></svg>Support</button></mat-toolbar>
navbar.component.scss
.mat-toolbar {
padding-top: 2px;
padding-left: 30px;
background-color: #fff;
}
::ng-deep .nav-tool-bar{
button{
.mat-button-focus-overlay{
opacity: 0!important;
}
.nav-bar-icon{
width: 16px;
}
span{
font-size: 15px;
}
}
.active-list-item{
background-color: #c79652;
span{
color: #fff;
font-size: 15px;
svg{
path{
color: #fff;
}
}
}
}
}
对更改 SCSS .active-list-item 背景颜色很重要。
我正在使用 angular5 应用程序,我面临同样的问题。当我浏览 Angular 文档时,它们提供了处理路由器事件的最佳解决方案。请查看以下文档。
Angular 中的路由事件 Angular5 中的路由事件
但特别是针对有问题的案例,我们需要 NavigationEnd 事件 Navigation End 事件 Angular
表示导航成功结束时触发的事件
这个怎么用?
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");
}
});
}
}
什么时候用这个?
在我的情况下,我的应用程序为所有用户(例如 users 、 Admins )共享公共仪表板,但我需要根据用户类型显示和隐藏一些导航栏选项。
这就是为什么每当 url 更改时,我需要调用服务方法,该方法根据响应返回登录的用户信息,我将进行进一步的操作。
以下类型的作品可能会为您带来棘手的问题。
// in constructor of your app.ts with router and auth services injected
router.subscribe(path => {
if (!authService.isAuthorised(path)) //whatever your auth service needs
router.navigate(['/Login']);
});
不幸的是,这在路由过程中比我想要的要晚。在重定向之前调用原始目标组件的 onActivate()
。
您可以在目标组件上使用 @CanActivate
装饰器,但它 a) 不是集中式的,并且 b) 不能从注入的服务中受益。
如果有人能提出一种更好的方法来在提交之前对路由进行集中授权,那就太好了。我相信一定有更好的方法。
这是我当前的代码(我将如何更改它以收听路由更改?):
import {Component, View, bootstrap, bind, provide} from 'angular2/angular2';
import {ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF} from 'angular2/router';
import {Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import { Todo } from './components/todo/todo';
import { About } from './components/about/about';
@Component({
selector: 'app'
})
@View({
template: `
<div class="container">
<nav>
<ul>
<li><a [router-link]="['/Home']">Todo</a></li>
<li><a [router-link]="['/About']">About</a></li>
</ul>
</nav>
<router-outlet></router-outlet>
</div>
`,
directives: [RouterOutlet, RouterLink]
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', component: Todo, as: 'Home' },
{ path: '/about', component: About, as: 'About' }
])
class AppComponent {
constructor(location: Location){
location.go('/');
}
}
bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'})]);
从 RC 5 开始我就这样做了
this.router.events
.map( event => event instanceof NavigationStart )
.subscribe( () => {
// TODO
} );
更简洁的方法是继承 RouteAware
并实现 onNavigationEnd()
方法。
它是名为 @bespunky/angular-zen 的库的一部分。
npm install @bespunky/angular-zen 让你的 AppComponent 扩展 RouteAware 并添加一个 onNavigationEnd() 方法。
import { Component } from '@angular/core';
import { NavigationEnd } from '@angular/router';
import { RouteAware } from '@bespunky/angular-zen/router-x';
@Component({
selector : 'app-root',
templateUrl: './app.component.html',
styleUrls : ['./app.component.css']
})
export class AppComponent extends RouteAware
{
protected onNavigationEnd(event: NavigationEnd): void
{
// Handle authentication...
}
}
RouteAware 还有其他好处,例如: ✨ 任何路由器事件都可以有一个处理方法(Angular 支持的路由器事件)。 ✨ 使用 this.router 访问路由器 ✨ 使用 this.route 访问激活的路由 ✨ 使用 this.componentBus 访问 RouterOutletComponentBus 服务
我用这种方式:
class ClassName {
constructor(private router: Router) {
router.events.subscribe((value) => {
// see this
console.log(value instanceof NavigationEnd)
});
}
}
如果您只想检查路由/查询参数更改,例如 localhost:4200/users/1?edit=1 到 localhost:4200/users/2?edit=0,您可以使用如下所示的 params observable。
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
}
}
您可以使用以下方法来检测路由更改:
从'@angular/router'导入{路由器,ActivatedRoute}; constructor(private route: ActivatedRoute) {} this.router.events.subscribe((event) => { if(event) { //do something } });
只需在 AppRoutingModule 上进行更改,例如
@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
exports: [RouterModule]
})
Angular 8. 检查当前路由是否为基础路由。
baseroute: boolean;
constructor(
private router: Router,
) {
router.events.subscribe((val: any) => {
if (val.url == "/") {
this.baseroute = true;
} else {
this.baseroute = false;
}
});
}
Angular 8.* 的简单答案
constructor(private route:ActivatedRoute) {
console.log(route);
}
event._root.children[0].value._routeConfig.data
获取数据我希望有更好的方法filter
运算符轻松过滤事件。router.events.pipe(filter(e => e instanceof NavigationEnd).subscribe((e) => { ... }
.subscribe(
之前忘记了右括号