angular - 共享服务无法从组件访问变量
问题描述
我正在尝试从自定义选择器上的外部组件调用函数。我找到了一种方法来实现这一点,但它不会识别组件中的任何变量。这就是我所做的:
选择器(声明为入口组件):
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 的按钮)
解决方案
add_LicenceComponent
为sharedService分配函数而不是返回 void。
另一件事是你得到TypeError因为在构造函数中尝试访问它时没有初始化服务。将其移至ngOnInit()并检查是否将它们添加到提供程序中
您需要对组件代码进行一些修改,如下所示,
constructor(public dialogService: DialogService, public sharedService: SharedFilterService) { }
ngOnInit() {
this.sharedService.add_LicenceComponent = this.addLicence;
}
addLicence(licence: any) {
console.log("Step 3") // Printed too
return (licence) => this.dialogService.openDialog(DialogComponent, licence).afterClosed().subscribe();
}
您可以在此stackblitz中查看示例 impl
推荐阅读
- java - 什么是删除重复项的好方法?
- reactjs - 在 React 组件中嵌入多个元素
- angular - 如何以编程方式折叠/展开引导折叠?
- python - 在特定条件下最后一次出现 Groupby 对象
- python - 基于 OpenAI Atari 中的操作的完成状态
- android - Android customlistview 反复滚动后崩溃
- arm - 在 uc/os-III 中进行上下文切换时内核寄存器布局错误
- ffmpeg - “AVIOContext”结构中“write_packet()/seek()”回调函数的return val是什么意思?
- java - 如何修复“IgniteCheckedException:查询执行失败:GridCacheQueryBean”?
- python - 无休止地打开和关闭网络摄像头?