如何使用 Nebular 对话框组件将数据传递给 Angular 组件?

How to pass data to Angular component using Nebular dialog Component?

我正在尝试将 objectData 从 componentA 发送到 DialogComponent 以编辑对象信息。

ComponentA 打开对话框并像这样传递数据:

export class ComponentA implements OnInit {
  constructor(private dialogService: NbDialogService) {}
  openDialog(data) {
    this.dialogService.open(DialogComponent, {
      context: {
        product: data,
      },
    });
  }
}

Nebular DialogComponent 类似:

export class DialogComponent implements OnInit {
  product: any; <--- the object that the dialogue will receive
  preSaleItem: any; <-- and turn into it, within the dialogue.

  constructor(
    private ref: NbDialogRef<DialogComponent>,
    private dataService: DataService,
  ) {
  }
  navigateToComponentB() { 
    this.dataService.data = this.preSaleItem;
    this.router.navigate(['/pages/componentB']);
    this.close();
  }

  close() {
    this.ref.close();
  }

在对话框中将用新信息填充 preSaleItem 并发送到 componentB。

我尝试了两种传输数据的方式,一种是通过服务

 export class DataService {
  data: any;

  constructor() {
    console.log(this.data); <----- the return is undefined
  }

什么都没有returns。 我认为 Nebular 组件对话框正在扼杀范围。

我将接收数据的 ComponentB 是:

 export class ComponentB implements OnInit {

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.preSaleItem = this.dataService.data;
    console.log(this.preSaleItem); <----- return is the same of the service
  }
 }

关于问题的加强信息: 我有一个 componentA 将产品传递到对话框并构建我之前提到的 preSaleItem,并且运行良好。

之后,当在对话框中构建preSaleItem 时,我需要将它发送到componentB。 但是按照我的想法,通过服务是行不通的。 :(

我尝试不通过对话框,使用 componentA 进行服务,并使用 componentB 的可观察变量,它起作用了。 但我需要数据才能通过对话框。

可能的解决方案是什么?

我找到了通过 angular 途径解决我的问题的方法。我会放一个简单的代码来演示。 使用状态属性。

export class DialogComponent implements OnInit {
  product: any; <--- the object that the dialogue will receive
  preSaleItem: any; <-- and transform, to move to componentB.

  constructor(private ref: NbDialogRef<DialogComponent>) {}

  navigateToOptionals() {
    this.fillPreSaleItem();
    this.router.navigate(['/pages/componentB', {
      state: {
        data: this.preSaleItem
      }
    });
    this.close();
  }

  close() {
    this.ref.close();
  }
}

它在我的组件 B 中表现如何

export class ComponentB implements OnInit {
  item: any;

  constructor() {}

  ngOnInit() {
    this.item = history.state.data;;
    console.log(this.item); <----- return my object that i want :)
  }
 }

我发现这个网站对我帮助很大! https://medium.com/ableneo/how-to-pass-data-between-routed-components-in-angular-2306308d8255