【发布时间】:2023-03-28 14:10:01
【问题描述】:
我正在尝试从自定义选择器上的外部组件调用函数。我找到了一种方法来实现这一点,但它不会识别组件中的任何变量。这就是我所做的:
选择器(声明为入口组件):
HTML:
<button (click)="addCertificate(searchInput)">Add</button>
TS:
constructor(public sharedService: SharedFilterService ) {
}
public addCertificate(payload: any) {
console.log("Step 1") // This is executed
if (this.sharedService.add_LicenceComponent) {
console.log("Step 2") // This one too
this.sharedService.add_LicenceComponent(payload);
}
}
服务(声明为提供者):
TS:
@Injectable()
export class SharedFilterService {
public add_LicenceComponent: any;
constructor() { }
}
最后是我无法访问任何变量的组件(许可证):
TS:
constructor(public dialogService: DialogService, public sharedService: SharedFilterService) {
this.sharedService.add_LicenceComponent = this.addLicence;
}
addLicence(licence: any): void {
console.log("Step 3") // Printed too
this.dialogService.openDialog(DialogComponent, licence).afterClosed().subscribe(); // Here I get this: ERROR TypeError: Cannot read property 'openDialog' of undefined
}
服务只是一个中介。我在 License 组件中使用了一个选择器(调用 addCertificate 的按钮)
【问题讨论】:
-
你只需要说
this.sharedService.add_LicenceComponent = payload;而不是this.sharedService.add_LicenceComponent(payload);,因为add_LicenceComponent只是一个变量。 -
你如何调用
addLicence函数以及从哪里调用? -
我相信最后一块
dialogService在调用addLicence函数时尚未初始化。你可以检查一下,dialogService 必须是未定义的。是吗? -
@Batajus add_LicenceComponent 是一个函数(我在最后一步调用的函数,我可以在那里打印值,但我无法访问“dialogService”)。我正在使用共享服务变量调用 addLicence
-
您是否遇到任何编译错误或运行时控制台错误..?
标签: angular typescript data-binding