gpt4 book ai didi

angular - 当路线改变 Angular 时如何运行函数?

转载 作者:行者123 更新时间:2023-12-03 09:54:38 25 4
gpt4 key购买 nike

我想根据Angular中的当前URL更改某个标题。所以component.ts看起来像这样:

import {Router} from '@angular/router';
//code
public name: string
constructor(
public router: Router
) {}
getName()
{
if(this.router.url === "/some_list")
{this.name = "List"}
else if(this.router.url === "/detail")
{this.name = "Detail"}
}


然后

<a>{{this.name}}</a>

现有的答案(例如 How to detect a route change in Angular?)无法告诉我更改路由(change = true或false)后如何做。
那么,每当URL更改时如何运行此函数,以便标题根据当前 View ?

最佳答案

您可以在subscribe中将router event转换为app.component.ts
每当您更改route时,它将触发。

  constructor(location: Location, router: Router) {
// decide what to do when this event is triggered.
router.events.subscribe(val => {
if (location.path() != "/something") {
// do something
} else {
// do something else
}
});
}

如果它多次调用,请尝试此操作
router.events.filter(event => event instanceof NavigationEnd).subscribe(val => { // here your code... })

注意:我尚未尝试过此

关于angular - 当路线改变 Angular 时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com