angular - 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>
解决方案
您应该监听路由器事件,并且通过使用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
}
});
}
推荐阅读
- mvvm - 为什么将 ViewModel 添加到我的 SwiftUI 应用程序后我的 UI 没有更新?
- javascript - 如何对平面列表中的数据进行排序
- python - 在curses中将文本框添加到pad?
- javascript - Jest - 测试 React 内存泄漏
- java - JavaFX 在 for 循环中使用预定义按钮时,它不会显示
- octave - 从 Octave 中的私有函数访问私有函数 [BUG]
- next.js - Nextjs 优化的 Image 组件的“imageSizes”配置选项实际上是做什么的?
- python - Python Pandas,获取所有其他电影的用户评分
- r - sf st_intersection 与 if else 函数和 st_extent
- python - 尽管添加了 time.sleep(),但 Selenium 无法定位元素