angular routerLink 按预期重定向到组件,但稍后 router.url 未返回当前 URL

angular routerLink redirects to component as expected, but later router.url not returning current URL

我的导航栏 About 中有一个 link 当我从我的主页 (/) 点击它时,浏览器重定向到 /about 路线 (About 组件)在我的应用程序中(无需重新加载 page/tab),这正是我正在寻找的。

在组件 About 中,我有一个要求,我需要根据我所在的 Url 动态加载内容。我尝试了很多获取当前 Url 的方法,但它总是 returns "/" 或者根本没有 return 任何东西。我所拥有的和我认为应该可以毫无问题地工作如下:

Link 在导航栏上

<a [routerLink]="['/about/who-i-am']" class="media d-flex align-items-center">
                <div class="icon icon-shape bg-gradient-primary rounded-circle text-white">
                  <i class="ni ni-palette"></i>
                </div>
                <div class="media-body ml-3">
                  <h6 class="heading text-primary mb-md-1">Who I am</h6>
                  <p class="description d-none d-md-inline-block mb-0">Small 2 line text goes in here about yourself and your blog/articles.</p>
                </div>
              </a>

About 组件 ts 文件:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-navbar-hero-content-section',
  templateUrl: './navbar-hero-content-section.component.html',
  styleUrls: ['./navbar-hero-content-section.component.css']
})
export class NavbarHeroContentSectionComponent implements OnInit {

  isWhoIam : Boolean = false;
  isHome : Boolean = false;
  constructor(private router: Router) { }

  ngOnInit(): void {

    var currentUrl: string;

    // Current Path:  company 
    // this.route.url.subscribe(url => {
    //   currentUrl = url[0].path;
    // });


    currentUrl = this.router.url;//the problem is here with currentUrl always returning "/" or the URL I came to this component/page from.

    console.log("current URL : " + currentUrl); 



    switch(currentUrl)
    {
      case "/" : 
      case "/home" :
      {
        this.isHome = true;
      }

      case "/about/who-i-am" : {
        this.isWhoIam = true;
      }
    }

  }

}


不知道这里会发生什么,我尝试了不同的方法来使用 Location/document 甚至 window 来获取当前 Url,它们似乎都是 [=56] =]一样/

更新:

现在我意识到当我点击 link 时 ngOnInit() 中的代码甚至没有 execute/run。 我向 console.log 添加了一个 Date.now() ,当我在“/about/who-i-am”和“/”之间来回单击时,我看到控制台日志显示在浏览器中相同的时间戳,它甚至不会改变。

实现此目的的一种方法是使用

this.location.path()

或者在你的情况下类似

this.location.path().inlcudes('home')

必须导入位置

import { Location } from '@angular/common';

并添加到构造函数

private location: Location,

更新 - 尝试将其添加到 ngOnInit:

 this.router.events.subscribe((evt) => {
      if (evt instanceof NavigationEnd) {
       // evt.url should update when the url gets updated
       // and you can use it whereever needed
      }
    });

您可以使用 window 得到 URL 类似的东西

let currentUrl = new URL(window.location.href);

console.log('current URL :', currentUrl);

有一个好的代码!