我想根据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/