首页 > 解决方案 > Observable:如何获取更改后的路径?

问题描述

我正在为我的项目构建面包屑(主页 > 日历)。我希望根据我所在的组件更新面包屑:

首页 > 日历

主页 > 访问我们

为此,我需要当前路径(我拥有),并且需要使用“Observables”来获取更改后的路径。

Q1) 我需要使用“Observables”来获取更改后的路径吗?

......这就是我卡住的地方!

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
	r:string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
  	// Got the current route, WORKS!
  	this.r = this.route.url;
  	// But, how do I use observables to get the changed path if user goes to a different page
  	this.route.url.subscribe((url: string)=>{
  		this.r = url;
  	})
  }

}
<div class="container">
	<div class="row">
		<div class="col-sm-8">
			<h1>musem</h1>
			<h6>ONTARIO</h6>
		</div>
		<div class="col-sm-2">
			<button class="btn btn-lg">
				<i class="fas fa-envelope"></i> Edit
			</button>
		</div>
		<div class="col-sm-2">
			<button class="btn btn-lg">
				<i class="fas fa-map"></i> Find
			</button>
		</div>
	</div>

	<nav aria-label="breadcrumb">
		<ol class="breadcrumb bg-transparent">
    		<li class="breadcrumb-item"><i class="fas fa-home"></i></li>
    		<li class="breadcrumb-item active" aria-current="page">{{r}}</li>
  		</ol>
	</nav>
	<hr>
</div>

标签: angularroutingobservable

解决方案


您应该监听路由器事件,并且通过使用NavigationEnd事件您可以通过访问evt.url哪个是更改路由的路径来获得正确的路径

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
......
ngOnInit() {
    this.router.events.subscribe((evt: any) => {
      if (evt instanceof NavigationEnd) {
        console.log(evt.url) //path of the route
      }
    });
}

推荐阅读