NavigationEnd 的 url 属性返回未定义(Angular 6)

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)

Saj*_*ran 8

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

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

  • 不适合我,收到以下错误“类型'(e:NavigationEnd)=> void'的参数不可分配给类型'(value:Event_2)=> void'的参数” (3认同)