我有一个服务和一个组件。在服务中,我试图打开一个对话框,在其中传递对服务中存在的方法的引用。例如:
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/