Angular 8-共享组件在其他组件调用两次

时间:2020-05-05 10:14:12

标签: angular typescript

因此,我有一个对话框组件及其父级共享一个可重用的组件。每次我从对话框中调用可重用组件的函数时,它也会从其父对象中调用它(两者都在ngAfterViewInit()上调用了该函数)是否知道如何防止父对象两次调用它?

父组件

@ViewChild('receivablesCustomerAcc', {static: false}) private customerAccountSelect: CustomerAccountSelectComponent;

public ngAfterViewInit(): void {
    this.customerAccountSelect.getCustomerAccounts();
}

对话框组件

@ViewChild('addReceivableCustomerAcc', {static: false}) private dialogcustomerAccountSelect: CustomerAccountSelectComponent;

private ngAfterViewInit(): void {
    this.dialogcustomerAccountSelect.getCustomerAccounts();
}

共享组件

export class CustomerAccountSelectComponent implements OnInit, OnDestroy {
    constructor(
        private customerService: CustomerApiService,
    ) { }

    public ngOnInit(): void {

    }

    public getCustomerAccounts() {
        // Retrieves data from API
    }
}

2 个答案:

答案 0 :(得分:0)

您可以将getCustomerAccounts()的内容从父级传递到对话框,而不是在对话框上调用该函数。您可以使用localstorage / sessionstorage对此进行设置,也可以在打开对话框时将其传递给对话框。 角材料对话框具有数据属性,可用于将数据发送到对话框。 看起来可能像这样:

 dialogRef = this.matDialog
        .open(SomeDialog, {
          data: { someData}
        }) 

然后可以使用以下方法检索数据:

 constructor(
    @Inject(MAT_DIALOG_DATA) public dialogData,
  ) { }
  ngOnInit() {

    const someData = this.dialogData.someData;

  }

希望能有所帮助。祝你好运。

答案 1 :(得分:0)

关于对话框的经验法则(根据我的看法)是:

  1. 对于对话框中所需的所有内容,请在调用程序组件中获取它,并将其作为对话框数据传递。
  2. 所有对话框动作都应将事件输出到负责实际业务逻辑的父组件。

第二条规则不适用于自足的对话框(在多个组件之间共享完全相同的逻辑)