作为新选项卡路由到组件并将数据传递到该组件

问题描述 投票:0回答:1

我有一个带有显示数据的网格的组件。其中一列包含数据行的 uniqueID,并且已模板化为带有 onclick 事件的按钮。 onclick 事件将打开一个新组件作为新选项卡/页面。这是我的 onclick 代码:

btnOpsE2EHistoryClick(uniqueID: string) {
   console.log('E2E history for UniqueID: ' + uniqueID);
   var navUrl = environment.siteURL + 'e2e-history/';
   window.open(navUrl + uniqueID, '_blank');
}

这工作正常,但我现在需要发送我不希望出现在 URL 中的附加数据。

btnOpsE2EHistoryClick(uniqueID: string, evType: string) {
   console.log('E2E history for event: ' + evType + ' - UniqueID: ' + uniqueID);
   var navUrl = environment.siteURL + 'e2e-history/';
   window.open(navUrl + uniqueID, '_blank'); //HOW DO I pass the evType so that it does not appear in URL.
}

我配置了以下路线:

{ path: 'e2e-history/:id', component: E2eHistoryComponent, title: 'E2E Log History' }

我该怎么办?

angular angular-routing
1个回答
0
投票

据我了解,根据您的情况,您希望在组件之间共享数据,并且不想将“evtype”参数作为路由 URL 的一部分。

组件之间的通信有多种方式:

  1. 使用事件发射器
  2. 使用服务
  3. 使用 NGRX 商店

就您而言,我建议通过服务进行通信。

以下是您应遵循的步骤:

  • 创建一个服务来在组件之间存储和共享数据。

  • 修改 btnOpsE2EHistoryClick 方法以存储附加数据 在打开新选项卡/窗口之前在服务中。

  • 创建一个组件来显示从服务接收到的数据
    新选项卡/窗口。

首先,创建一个服务来存储和共享数据(不要忘记在模块中分配服务):

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataSharingService {
  private eventData: any;

  constructor() { }

  setEventData(data: any) {
    this.eventData = data;
  }

  getEventData() {
    return this.eventData;
  }
}

接下来,修改您的组件以使用该服务:

import { DataSharingService } from 'path/to/data-sharing.service';

constructor(private dataSharingService: DataSharingService) {}

btnOpsE2EHistoryClick(uniqueID: string, evType: string) {
   console.log('E2E history for event: ' + evType + ' - UniqueID: ' + uniqueID);
   
   // Store additional data in the service
   this.dataSharingService.setEventData({ uniqueID: uniqueID, evType: evType });

   // Open the new tab/window
   var navUrl = environment.siteURL + 'e2e-history/';
   window.open(navUrl + uniqueID, '_blank');
}

最后,在新选项卡/窗口的组件中,从服务中检索数据:

import { DataSharingService } from 'path/to/data-sharing.service';

constructor(private dataSharingService: DataSharingService) {}

ngOnInit() {
  // Retrieve data from the service
  const eventData = this.dataSharingService.getEventData();
  console.log(eventData); // Do whatever you want with the data
}

此方法可确保附加数据在组件之间共享,而不会在 URL 中公开。

© www.soinside.com 2019 - 2024. All rights reserved.