繁体   English   中英

通过在 Angular 导航中传递 ID 来检索对象

[英]Retrieve the object by passing the ID in Angular navigation

我是 angular 的新手,我自己学习 angular。 我怀疑将数据从一个组件传递到另一个组件。

在我下面的代码中,我使用 click 方法传递 ID 我有一个包含对象数组的示例 JSON 对象。 假设我有 3 个具有不同 ID 的对象,并且我正在使用*ngFor循环数据。 现在使用(click)方法我传递我的ID如下

goToWorkOrderDetails(id): void {
    this.router.navigate(['/work-orders/work-order-details', { id }]);
 }

在我的下一个页面,我检索ID使用

this.route.params.subscribe((params: Params)=> this.user.id= this.params['id'])

有没有办法检索包含该id的完整反对意见?

您可以使用角度服务。 将您的对象保存在那里并在您的新组件上检索它。 如果您想通过 url 发送它们,您可以使用NavigationExtras

主页组件

import {Router,NavigationExtras} from '@angular/router';

const navigationExtras: NavigationExtras = {
  state: {
   id:id,
   name: name,
   ....other properties of your object here
 }
};
this.router.navigate(['/work-orders/work-order-details'], navigationExtras);

新组件

constructor(private router: Router) {
   const navigation = this.router.getCurrentNavigation();
   const state = navigation.extras.state as {
    id: string,//or whatever you want
    name: string,
   };
console.log("id: " + state.id ",name:" + state.name)
}

暂无
暂无

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

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