【问题标题】:How to pass data to Angular component using Nebular dialog Component?如何使用 Nebular 对话框组件将数据传递给 Angular 组件?
【发布时间】:2020-12-30 08:28:41
【问题描述】:

我正在尝试将我的 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 并将沙子添加到组件 B。

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

 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
  }
 }

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

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

我尝试不通过对话框,将组件A 用于服务,并为组件B 使用可观察的变量,并且它起作用了。 但我需要数据通过对话框。

有哪些可能的解决方案?

【问题讨论】:

    标签: angular typescript nebular ngx-admin


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2017-10-11
      • 2016-08-18
      • 2021-12-15
      相关资源
      最近更新 更多