如何在 angular 中更改路线时 运行 函数?

How to run a function when a route changes in angular?

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

现有的答案,如 无法告诉我在路由更改(更改 = true 或 false)后如何做某事。 那么,每当 url 更改时,我如何 运行 这个函数,以便标题根据当前视图显示?

您可以在 app.component.tssubscriberouter event。 每次更改 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... })

注意:这个我没试过


去这个StackBlitz link

在路由器的每个导航启动事件中,您可以获得 url 和触发功能。在你里面 app.component.ts

ngOnInit(){
   this.router.events.subscribe(event =>{
      if (event instanceof NavigationStart){
         console.log(event.url)
         this.routerChangeMethod(event.url);
      }
   })
}

routerChangeMethod(url){
  this.title = url;
}

你 app.component.html 是..

{{title}}

<router-outlet></router-outlet>

作为一种好的做法,您应该 one component per route

RouterModule.forRoot([
    { path: 'products', component: DetailComponent },
    { path: 'shopping-cart', component: SomelistComponent }
])

如果你坚持这种做法,那么你就会有一个关注点分离。

然后根据你刚刚为你的组件设置header的路由。

您可以在此处阅读有关 routing 的更多信息。

这样试试:

Working Demo

.html

<a routerLinkActive="active" routerLink="/some_list">Home</a> |
<a routerLinkActive="active" routerLink="/detail">Catalog</a>

<router-outlet (activate)="getName()"></router-outlet>

.ts

getName() {
  if (this.router.url.includes("some_list")) {
      this.name = "some_list";
  } else if (this.router.url.includes("detail")) {
      this.name = "detail";
  }
  alert(this.name);
}