gpt4 book ai didi

Angular 如何使用路由传递数据

转载 作者:行者123 更新时间:2023-12-05 09:04:52 25 4
gpt4 key购买 nike

我有两个组件如下:

  1. 我在其中显示表格的产品表格
  2. 产品消息,我在其中显示点击表格的结果

我让组件与输入和输出进行通信,一切都运行良好。

现在我想尝试通过路由传递数据的新方法。

product-table.html

<!-- Symbol Column -->
<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef>Symbol</th>
<td mat-cell *matCellDef="let element">{{element.symbol}}</td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"
(click)="selected(row)" (click)="navigate(row)"></tr> // i try with navigate method here

product-table.ts

export class ProductTableComponent implements OnInit ,OnDestroy{

displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
public dataSource!: MatTableDataSource<Product>;

private sub: Subscription = new Subscription;

@Output() selectedArrayEnfant2 = new EventEmitter();

constructor(private productService: ProductService, private router: Router) { }

ngOnInit(): void {
this.getAllProduct();
}

getAllProduct() {
let resp = this.productService.getAll();
this.sub =resp.subscribe(result => {
this.dataSource = new MatTableDataSource<Product>();
this.dataSource.data = result as Product[];
});
}

selected(row:Product) {
this.selectedArrayEnfant2.emit(row);
}

navigate(row:Product) {
this.router.navigate(['/msg', row]); // i try something here but this method open the new page instead just pass data in message component via routing
}

product.message.ts

export class ProductMessageComponent implements OnInit, OnChanges {

@Input() public selectedArrayEnfant1!: Product;

constructor() { }

ngOnChanges(changes: SimpleChanges): void {}

ngOnInit(): void {

}
}

product.message.html

<h1>{{selectedArrayEnfant1?.name}}</h1>

我在 product.page.html 中显示这两个组件

product.page.html

<div class="center">
<app-product-table (selectedArrayEnfant2)="receive($event)"></app-product-table>
<app-product-message [selectedArrayEnfant1]="selectedArrayParent"></app-product-message>
</div>

app.routing.module

const routes: Routes = [
{
path: '',
redirectTo: '/hello', pathMatch: 'full'
},
{
path: 'product',
loadChildren: () => import('./components/product/module/product.module').then(m => m.ProductModule),
},
{
path: 'msg',
component: ProductMessageComponent
}
];

最佳答案

如果你想传递一个对象(这里假设row是一个对象),你需要将它字符串化为一个字符串并作为一个字符串传递。获取到之后,需要再次解析成对象。

因此,对于导航,请执行以下操作:

this.router.navigate(['/msg', {my_object: JSON.stringify(row)}]);

然后在 recipient(msg) 组件中解析它

this.Obj = JSON.parse(this.route.snapshot.paramMap.get('my_object'));

像这样更改构造函数参数:

constructor(
...
private router: Router,
private route: ActivatedRoute
) { }

关于Angular 如何使用路由传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68103260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com