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

问题描述

我正在尝试将我的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
  }

什么也没有返回。 我认为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。 但是我认为通过服务的方式行不通。 :(

我尝试不通过对话框使用组件A进行服务,而使用可观察的var进行组件B的对话,它起作用了。 但是我需要数据才能通过对话框。

可能的解决方案是什么?

解决方法

我找到了一种通过角度路线解决问题的方法。我将用一个简单的代码来演示。 使用状态属性。

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();
  }
}

它在我的componentB中怎么样

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