angular - 传递正确的上下文以在 Angular 的对话数据中运行

标签 angular typescript

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

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

编辑 我通过将 this 作为 that 传递给 data 来解决 例如,

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

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

最佳答案

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

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the this keyword always represents the object that defined the arrow function.

你的代码会像这样被修改

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.. 
   } 
}

请找到details here .

谢谢。

关于angular - 传递正确的上下文以在 Angular 的对话数据中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59754380/

相关文章:

reactjs - 构造函数中的 setState 无法正常工作 : ReactJS

kendo-ui - TypeScript 定义,其中属性类型已知但名称*不是*

typescript - 在 Typescript 中如何忽略 NPM 包的内置声明文件?

angular - 函数 typescript 后停止滚动事件

forms - Angular 2 - 单击以编辑表单字段

Angular 单元测试 - 在 ViewChild 中引用/模拟指令

angular - 解析从 HTTP catch 返回的错误 - Angular 2

angularjs - Angular 2(Ionic 2)在显示页面时调用页面中的函数

javascript - 使用 .getElementsByClassName() 的 Angular 2 通过存在返回空选择

javascript - TypeORM 自定义装饰器