首页 > 解决方案 > 传递正确的上下文以在 Angular 的对话框数据中运行

问题描述

我有一个服务和一个组件。在服务中,我试图打开一个对话框,在该对话框中我传递对服务中存在的方法的引用。例如:

export class SomeService {
   private test = 10;

   public getTest() {
      return this.test;
   }

   openDialog() { 
      const dialogRef = someExternalService.open(MyComponent, {
      disableClose: true,
      data: {
        someData: 'hello world',
        test: this.getTest
      }
    });
}

export class MyComponent {
   constructor(@Inject(DIALOG_DATA) data: any) { 
       console.log(data.data.someData); //prints 'hell world' correctly
       console.log(data.data.test()); //prints undefined.. 
   } 
}

问题是,当test调用该方法时,this函数中的 被认为是data.data,而不是SomeService上下文。

如何确保getTest在正确的上下文中调用它?

编辑 我通过传递到 So 例如this解决了,thatdata

  data: {
    someData: 'hello world',
    test: this.getTest,
    that: this
  }

然后像 data.data.that.getTest()正确打印一样调用它,但我觉得我可以在不传递整个 Service 对象的情况下做到这一点?

标签: angulartypescript

解决方案


使用JavaScript 箭头函数来声明您的函数。除了提供简洁的语法来编写函数外,箭头函数还使您摆脱了this关键字的绑定。这是 w3schools 的解释

常规函数中,this 关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何东西。

对于箭头函数,this 关键字始终表示定义箭头函数的对象。

你的代码会被这样修改

export class SomeService {
   private test = 10;

   public testFunc = ()=>{
      return this.test;
   };

   openDialog() { 
      const dialogRef = someExternalService.open(MyComponent, {
      disableClose: true,
      data: {
        someData: 'hello world',
        test: this.testFunc
      }
    });
}

export class MyComponent {
   constructor(@Inject(DIALOG_DATA) data: any) { 
       console.log(data.data.someData); //prints 'hell world' correctly
       console.log(data.data.test()); //prints undefined.. 
   } 
}

请在此处找到详细信息。

谢谢。


推荐阅读