html - 从另一个组件调用函数时,函数内部的对象未执行
问题描述
抱歉无法正确命名我的问题。让我正确解释我的问题。我有 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。问题是什么?
解决方案
假设你将组件 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();
}
}
推荐阅读
- powershell - 如何为经过身份验证的用户授予具有 powershell 的文件夹的完全权限
- javascript - 如何使用 ngfor 迭代对象
- java - 如何将目标添加到 captureRequestBuilder 以及如何处理每一帧?
- javascript - Firebase 云功能 - 如何获取模型数据
- google-maps - 无法解析模块“react-native-google-place-picker”
- dax - DAX WeekNum 超过 1 年?
- xamarin.forms - 在默认的空白应用程序中找不到命名空间“应用程序”
- sql - UNPIVOT 通过数据库链接返回错误结果
- excel - 如果单元格为空,则删除行
- xml - sed 在 xml 文件中附加字符串