首页 > 解决方案 > 从另一个组件调用函数时,函数内部的对象未执行

问题描述

抱歉无法正确命名我的问题。让我正确解释我的问题。我有 2 个组件,说 A 和 B。在 BI 中有一个saveIndCustData发出和保存数据的功能。

export class CustomerformComponent implements OnInit {
@Output()
savedIndCustomer: EventEmitter<any> = new EventEmitter<any>();
saveIndCustData() {
const savedIndCustomer = {
  prefix: this.prefix,
  nameType: this.indCustNameType,
  firstName: this.firstName,
  middleNAme: this.middleName,
  lastName: this.lastName,
  gender: this.gender,
  dateOfBirth: this.parseDate(this.dateOfBirth.toString()),
  citizenship: this.citizenship
};

this.savedIndCustomer.emit(savedIndCustomer);
this.snackbar.open('Customer Info Saved,Click on Next', 'Close', {
  duration: 5000
});
}
}

我现在从组件 A 调用该函数。

import { CustomerformComponent } from './forms/customerform/customerform.component';
constructor(private custComp: CustomerformComponent) {}
saveCustomerForm(): void {
this.custComp.saveIndCustData();
}

我将数据发送到服务类

@Output()
savedIndCustomer: EventEmitter<any> = new EventEmitter<any>();

服务等级

public addDynamiIndCustomerComponent() {
const factory = this.factoryResolver.resolveComponentFactory(CustomerformComponent);
const component = factory.create(this.rootViewContainer.parentInjector);
component.instance.savedIndCustomer.subscribe(data => {
  console.log(data);
  // Insert Individual Customer Type
  this.custFullDetails.customerType = 'individual';
  this.custFullDetails.individualCustomer.dateOfBirth = data.dateOfBirth;
  this.custFullDetails.individualCustomer.citizenship = data.citizenship;
  this.custFullDetails.individualCustomer.gender = data.gender;
  this.custFullDetails.individualCustomer.individualName.push({
    prefix: data.prefix,
    firstName: data.firstName,
    middleName: data.middleName,
    lastName: data.lastName,
    agreementId: data.agreementId,
    nameType: data.nameType
  });
  console.log(this.custFullDetails.individualCustomer);
});
this.rootViewContainer.insert(component.hostView);
}

我的问题是,如果我saveIndCustData从组件 B 调用该函数,它会将数据推送到数组const savedIndCustomer{ ... }中并调用服务类。但是,当我从组件 A 调用相同的函数时,它不会调用函数const savedIndCustomer{ ... }内部的方法,saveIndCustData()并且服务类方法不会将数据保存在数组中,而只是显示 snakbar。问题是什么?

标签: htmlangulartypescript

解决方案


假设你将组件 B 放在组件 A 的 html 中,那么你应该像这样为组件 B 做一个引用

A.component.html:

...
    <B #bcmp></B>
...

并像这样使用 @ViewChild 将其注入 A.component.ts

A.component.ts:

@Component({
    selector: 'A',
    templateUrl: './A.component.html',
    styleUrls: ['./A.component.scss']
})
export class AComponent implements OnInit {
    @ViewChild("bcmp") bcmp : B
    ngOnInit(): void {
        // by this way you can use any method existant in B component
        this.bcmp.saveIndCustData();
    }
}

推荐阅读