首页 > 解决方案 > 共享服务无法从组件访问变量

问题描述

我正在尝试从自定义选择器上的外部组件调用函数。我找到了一种方法来实现这一点,但它不会识别组件中的任何变量。这就是我所做的:

选择器(声明为入口组件):

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 的按钮)

标签: angulartypescriptdata-binding

解决方案


add_LicenceComponentsharedService分配函数而不是返回 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


推荐阅读