The*_*Guy 5 javascript router rxjs typescript angular
我对前端的东西比较陌生,我一直在玩 Angular 6,所以我在使用以下组件时面临的问题是NavigationEnd返回undefined,我不知道为什么:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
currentUrl: string;
constructor(private router: Router) {
router.events.subscribe(
(navEnd: NavigationEnd) => this.currentUrl = navEnd.url
);
}
}
Run Code Online (Sandbox Code Playgroud)
router.events
有不同的事件,如果您需要获取 NavigationEnd,则需要按如下方式过滤。尝试这个,
router.events
.pipe(filter(e => e instanceof NavigationEnd))
.subscribe((e: NavigationEnd) => {
this.currentUrl = e.url;
});
Run Code Online (Sandbox Code Playgroud)