抱歉,无法正确回答我的问题。
让我正确解释我的问题。
我有2个成分,分别是A和B。
在B中,我有一个函数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);
}
我的问题是,如果我从组件B调用saveIndCustData
函数,它将数据推入数组const savedIndCustomer{ ... }
并调用服务类。
但是,当我从组件A调用相同的函数时,它不会调用const savedIndCustomer{ ... }
函数内部的saveIndCustData()
方法,并且服务类方法不会将数据保存在数组中,而只是显示了snakbar。
有什么问题吗?
答案 0 :(得分:1)
假设您将组件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();
}
}