【问题标题】:Get the URL with Angular Router使用 Angular 路由器获取 URL
【发布时间】:2019-09-05 13:37:41
【问题描述】:

我需要在位于应用程序组件中的组件(我的导航组件)中获取我当前的路线(使用路由器),但由于它已经加载,单击时不会刷新,我在导航组件中的功能是'不返回任何新的 URL。 如何在导航组件中使用新 URL?

这是我的应用组件:

<app-nav></app-nav>
<body>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</body>

这是我的导航组件 (.ts):

ngOnInit() {
    console.log(this.router.url);
    if(this.router.url == "/") {
      this.color = "large";
      this.logoPath = "assets/logos/w-logo-full.png";
    } else {
      this.color = "small";
      this.logoPath = "assets/logos/c-logo-full.png";
    }

当我的 app-nav 在每个组件中时它都可以工作,但是自从我移动它之后它就不再工作了..

【问题讨论】:

  • 你的 NavComponent 不包含在你的路由中,所以你无法获取当前路由,我建议你在 app.component 中获取当前根并作为参数传递给导航栏
  • 如果我将 ngOnInit 移动到 nav.component.ts 中,同样的问题:在页面更改时,没有返回新的 URL..

标签: javascript angular typescript angular-router angular8


【解决方案1】:

您可以使用可观察的路由器服务事件

app.component

  constructor( public router: Router,) {
  }

  public ngOnInit(): void {
    this.router.events.subscribe(e => {


      if (e instanceof NavigationEnd) {
        console.log(this.router.url);
        // ... 
      }

    });
  }

NavigationEnd 导航成功结束时触发的事件。

【讨论】:

  • 使用 .events 但在 NavigationEnd 上出现参考错误:未定义 NavigationEnd
  • @GermainWeb 确实添加了导入语句?` import { NavigationEnd, NavigationStart, Router } from '@angular/router';`
  • 你成功了!
【解决方案2】:

您需要订阅ActivatedRoute服务

类似这样的: 添加ActivatedRoute:

 constructor(
        protected route: ActivatedRoute,
        ...) {
   }

添加订阅:

this.route.url.subscribe(value => {
     ....
    });

【讨论】:

  • 在我的应用组件中还是导航一个?
  • @GermainWeb 您需要添加订阅者要在哪里运行 if。我猜在导航组件中。
【解决方案3】:
import {
  ActivatedRoute
} from '@angular/router';

export class AppComponent implements OnInit {
  constructor(private route: ActivatedRoute) {
    console.log("current route is " + route);
  }
}

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2017-01-13
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多