Angular 如何使用路由传递数据

Angular how to pass data using route

我有两个组件如下:

  1. product-table 我在其中显示 table
  2. product-message 我在其中显示点击 table
  3. 的结果

我让组件与输入和输出进行通信,一切正常。

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

产品-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

产品-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)}]);

然后在收件人(消息)组件中将其解析回来

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

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

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

传递数据

const queryParams = { ids: row };
this.router.navigate(['/product/msg'], { queryParams: queryParams });

获取数据

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.name = params['name'];
  });
}

路线

  { 
    path: 'product/msg',
    component: ProductMessageComponent
  }