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

标签 javascript angular typescript rxjs router

我对前端的东西比较陌生,我在玩 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
    );
  }
}

最佳答案

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

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

关于javascript - NavigationEnd 的 url 属性返回未定义(Angular 6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573947/

相关文章:

angular - ts(6385) 订阅 已弃用

asp.net - 使用 Visual Studio 2015 在 gulp 中检测发布/调试

javascript - 我想在离开页面之前显示模态弹出窗口

javascript - 使用 transform :scale on parent, 时,子元素的下拉列表位于另一行下方

angular - 异步管道不会将对象数据填充到模板中

javascript - typescript ,使用没有构造函数的类

javascript - 为什么 TypeScript 使用 "Like"类型?

javascript - 尝试定位无序列表中的特定数字 LI 项目并附加 html

javascript - 如何使用 azure 函数和 cosmos Node sdk 检查 cosmosDB 中的项目是否已过期?

Angular 更新 10.2 到 11