简体   繁体   English

哪里是在 Angular 中捕获路由参数的最佳位置

[英]where is the best place to capture params of routes in Angular

I have this layout我有这个布局

布局

Each time I select a project in sidenav component I must show the relational data of that selected project in the maincontent component每次我 select 在 sidenav 组件中的一个项目时,我必须在 maincontent 组件中显示该选定项目的关系数据

The issue is that I have this in sidenav问题是我在sidenav中有这个

关联

that is, each selected project goes to a new route, so in the maincontent component I get the params of this route in ngOnInit也就是说,每个选定的项目都会转到一条新路线,因此在 maincontent 组件中,我在 ngOnInit 中获得了这条路线的参数

ngOnInit(): void {
let id=this.route.snapshot.paramMap.get('id');

But this code only executes once when I select another project this code does not execute.但是当我 select 另一个项目此代码不执行时,此代码仅执行一次。

Add a subscription to your component (I guess, PlanificadorComponent or similar), subscriping ActivatedRoute :添加订阅到您的组件(我猜是PlanificadorComponent或类似的),订阅ActivatedRoute

private subscription: Subscription;
id: string;

constructor(private route: ActivatedRoute) {
}

ngOnInit(): void {
  this.subscription = this.route.params.subscribe(params => {
    this.id = params.id;
  });
}

ngOnDestroy(): void {
  if (this.subscription) {
    this.subscription.unsubscribe();
  }
}

See also Getting route information :另请参阅获取路线信息

Often, as a user navigates your application, you want to pass information from one component to another.通常,当用户浏览您的应用程序时,您希望将信息从一个组件传递到另一个组件。 For example, consider an application that displays a shopping list of grocery items.例如,考虑一个显示杂货购物清单的应用程序。 Each item in the list has a unique id.列表中的每个项目都有一个唯一的 ID。 To edit an item, users click an Edit button, which opens an EditGroceryItem component.要编辑一个项目,用户单击一个编辑按钮,这将打开一个 EditGroceryItem 组件。 You want that component to retrieve the id for the grocery item so it can display the right information to the user.您希望该组件检索杂货项目的 id,以便它可以向用户显示正确的信息。

You can use a route to pass this type of information to your application components.您可以使用路由将此类信息传递给您的应用程序组件。 To do so, you use the ActivatedRoute interface.为此,您使用 ActivatedRoute 接口。

That seems to match your requirement.这似乎符合您的要求。 There is also a step by step guide provided.还提供了分步指南。

The problem using snapshot is that this method only executes once in ngOnInit when the component is initialized.使用快照的问题是该方法只在组件初始化时在 ngOnInit 中执行一次。

To watch any changes in param routes the option is using an Observable with parmMap要观察参数路由的任何变化,该选项是使用带有 parmMap 的 Observable

ngOnInit(){
this.route.paramMap.subscribe(
  params => {
    const id = params.get('id');

    console.log('MainContent:Proyecto Seleccionado: ', id);

    this.dataService.getDatosCabeceraProyecto(id)
    .subscribe(
      (data:Proyecto)=>this.proyecto=data,
      (err:any)=>console.log(err),
      ()=>console.log('MainContent: datos de proyecto recogidos')
    );
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM