【问题标题】:Angular Routing: Retrieving the latest route link inside the component stateAngular Routing:检索组件状态内的最新路由链接
【发布时间】:2021-07-03 04:37:41
【问题描述】:

为了提供一个最简单的示例,假设我在 RouterModule.forRoot 中指定了以下两条路由,它们都链接到同一个组件 SomeComponent

const routes: Routes = [{ path: 'one-path',  component: SomeComponent },
{ path: 'another-path', component: SomeComponent }];

在应用程序 html 模板中,我有两个路由器链接以及路由器插座

<a routerLink="/one-path">someLink</a> 
<a routerLink="/another-path">anotherLink</a>
...
<router-outlet> </router-outlet>

我想要的是将组件呈现在页面上的最后一个路由器链接路径作为 SomeComponent 状态的一部分。目的是根据使用的链接显示略有不同的视图。

export class SomeComponent implements OnInit {

  let route_path = ... //this should either be 'one-path' or 'another-path' depending on which link was clicked

}

如何做到这一点?

【问题讨论】:

    标签: angular2-routing


    【解决方案1】:

    您需要订阅可观察到的活动路由 url。初始化组件时,route_path 将是“一个路径”或“另一个路径”,具体取决于单击的链接或您是否在主路径上。

    export class SomeComponent implements OnInit { 
        route_path ='';  
    
        constructor(private route: ActivatedRoute) { }
    
       ngOnInit() {
    
        this.route.url.subscribe((url) => {
             this.route_path = (url.length > 0 )? url[url.length-1].path: '';
          });
    
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多