【问题标题】:Observable: How to get the changed path? [closed]Observable:如何获取更改后的路径? [关闭]
【发布时间】:2019-03-04 03:40:20
【问题描述】:

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

首页 > 日历

首页 > 访问我们

为此,我需要当前路径(我拥有),并且我需要使用“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>

【问题讨论】:

    标签: angular routing observable


    【解决方案1】:

    你应该在你想要监听变化的组件中注入Router并订阅router.events。我在下面链接了一个 stackblitz 演示。

    演示:https://stackblitz.com/edit/angular-router-basic-example-tpucgr?file=app/app.component.ts

    恕我直言,如果您在 app.component.ts 中创建一个面包屑组件会更好。为面包屑创建服务。在此服务中注册面包屑组件的实例,然后将此服务注入到您希望面包屑更改的组件中,并调用服务内部的方法,该方法依次调用面包屑组件的方法来更新面包屑。

    另见answer

    【讨论】:

      【解决方案2】:

      你应该监听路由器事件,并且通过使用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
            }
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 2023-03-02
        • 1970-01-01
        相关资源
        最近更新 更多