从 angular 中的自定义指令中获取当前路线
Getting the current route from within custom directive in angular
我正在尝试执行自定义指令。我想在 ngOnInit() 中获取当前路线。我发现了一些如下代码。
@Directive({
selector: '[appLeftMenuActive]'
})
export class LeftMenuDirective implements OnInit {
@Input('appLeftMenuActive') pathKey;
@HostBinding('class')
elementClass;
constructor(private elRef:ElementRef,private route: Router) {
}
ngOnInit(): void {
this.route.events.subscribe((data:any) => {
console.log(data.url)
});
}
}
此代码运行 console.log 三次 ,我不知道为什么。有任何想法吗?或从该指令中获取当前活动路线的更好方法?
<a class="nav-link" [appLeftMenuActive]="'game'" routerLinkActive="active" [routerLink]="['/game/list']">
控制台日志被多次调用,因为路由器发出多个事件:
- GuardsCheckEnd
- GuardsCheckStart
- 导航取消
- 导航结束
- 导航错误
- 导航开始
- 解决结束
- 解决开始
- 路线已识别
如果您在设置路由时使用选项,则可以跟踪路由器的工作原理:
import {
ExtraOptions,
RouterModule,
Routes
} from '@angular/router';
export const options: ExtraOptions = {
enableTracing: true,
};
@NgModule({
imports: [
RouterModule.forRoot([], options),
],
exports: [ RouterModule ],
})
export class AppRoutingModule { }
您可以按事件类型过滤可观察事件的输出,例如:
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(...)
您可以找到有关路由器事件的更多信息:
我正在尝试执行自定义指令。我想在 ngOnInit() 中获取当前路线。我发现了一些如下代码。
@Directive({
selector: '[appLeftMenuActive]'
})
export class LeftMenuDirective implements OnInit {
@Input('appLeftMenuActive') pathKey;
@HostBinding('class')
elementClass;
constructor(private elRef:ElementRef,private route: Router) {
}
ngOnInit(): void {
this.route.events.subscribe((data:any) => {
console.log(data.url)
});
}
}
此代码运行 console.log 三次 ,我不知道为什么。有任何想法吗?或从该指令中获取当前活动路线的更好方法?
<a class="nav-link" [appLeftMenuActive]="'game'" routerLinkActive="active" [routerLink]="['/game/list']">
控制台日志被多次调用,因为路由器发出多个事件:
- GuardsCheckEnd
- GuardsCheckStart
- 导航取消
- 导航结束
- 导航错误
- 导航开始
- 解决结束
- 解决开始
- 路线已识别
如果您在设置路由时使用选项,则可以跟踪路由器的工作原理:
import {
ExtraOptions,
RouterModule,
Routes
} from '@angular/router';
export const options: ExtraOptions = {
enableTracing: true,
};
@NgModule({
imports: [
RouterModule.forRoot([], options),
],
exports: [ RouterModule ],
})
export class AppRoutingModule { }
您可以按事件类型过滤可观察事件的输出,例如:
this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(...)
您可以找到有关路由器事件的更多信息: