【问题标题】:Shared service can't reach variables from component共享服务无法从组件访问变量
【发布时间】: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


【解决方案1】:

sharedServiceadd_LicenceComponent 分配函数,而不是返回 void。

另一件事是您得到 TypeError,因为在 constructor 中尝试访问服务时未初始化服务。将其移至 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2012-04-10
    • 2011-04-07
    • 2015-07-25
    相关资源
    最近更新 更多