NavigationEnd url 属性 returns 未定义 (Angular 6)

url property of NavigationEnd returns undefined (Angular 6)

我对前端的东西比较陌生,我在玩 Angular 6,所以我面临以下组件的问题是 NavigationEnd returns 未定义 我不知道为什么:

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
    );
  }
}

router.events有不同的事件,如果需要获取NavigationEnd则需要如下过滤。试试这个,

 router.events
      .pipe(filter(e => e instanceof NavigationEnd))
      .subscribe((e: NavigationEnd) => {
        this.currentUrl = e.url;       
 });

您需要检查您从订阅方法接收到的事件类型。

你还需要使用this来访问路由器(它是一个私有变量)

 constructor(private router: Router) {
this.router.events
  .subscribe((event) => {
    if (event instanceof NavigationEnd) {
      this.currentUrl = event.url
      console.log('NavigationEnd:', event);
    }
  })

我认为您要实现的目标如下。

this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd),
    map(() => this.activatedRoute)
 ).subscribe((event) => {
       this.currentUrl = event.url
});

在构造函数中注入 ActivatedRoute。

快速修复,

更改代码

(navEnd: NavigationEnd) => this.currentUrl = navEnd.url

(navEnd: NavigationEnd) => this.currentUrl = router.url

只需更改一行即可使其在 Angular 7

上运行
router.events.subscribe(() => this.currentUrl = this.router.url)

您也可以在异步中使用它来检查条件,

async getUrl(){
    this._router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((path:NavigationEnd)=>{
    console.log("path",path);  
    this.activeUrl=path.url.split('/');
    this.activeUrl.splice(0,1)
    console.log("activeurl",this.activeUrl);
    return this.activeUrl;
    })
}
this.getUrl().then(()=>{
    if(this.activeUrl[1]=='admin'){
    //your code goes here
    }
})