【问题标题】:How to run a function when a route changes in angular?当路线角度发生变化时如何运行函数?
【发布时间】:2020-04-08 18:19:26
【问题描述】:

我想根据 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? 无法告诉我在路由更改后如何做某事(更改 = 真或假)。 那么如何在 url 发生变化的时候运行这个函数,让标题按照当前的视图呢?

【问题讨论】:

标签: angular routing angular-router


【解决方案1】:

您可以在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... })

注意:我没有试过这个


【讨论】:

  • 这将为所有不同的事件多次调用。检查日志。
【解决方案2】:

去这个StackBlitz link

在路由器的每个导航启动事件中,您都可以获得 url 和 fire 函数。在你的 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>

【讨论】:

    【解决方案3】:

    作为一个好的做法,您应该拥有one component per route

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

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

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

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

    【讨论】:

    • 我完全同意 - 每个规则我已经有一个组件,但我有一个额外的组件供 contenttab 在这些组件之间导航 - 对于这个 contenttabs 的特殊用例,我需要标题跨度>
    【解决方案4】:

    试试这样:

    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);
    }
    

    【讨论】:

    • 我想我读到在标记中使用方法是不好的做法。这些方法在渲染阶段会被调用很多次。请查看下面 GaurangDhorda 的答案
    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 2023-03-06
    • 2018-05-07
    • 2018-03-30
    • 2022-11-26
    • 1970-01-01
    • 2019-12-09
    相关资源
    最近更新 更多