angular - 传递正确的上下文以在 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
解决了,that
data
data: {
someData: 'hello world',
test: this.getTest,
that: this
}
然后像
data.data.that.getTest()
正确打印一样调用它,但我觉得我可以在不传递整个 Service 对象的情况下做到这一点?
解决方案
使用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..
}
}
请在此处找到详细信息。
谢谢。
推荐阅读
- python - 内部函数中的模拟默认参数值
- sql - Linq Group By Sum 基于条件
- angularjs - 如何销毁 angularjs 指令?
- python - Python中的可选链接
- vbscript - VBScript 添加验证对象运行时错误
- vb6 - VB6 是否能够将对象“转换”为“打印机”类型?
- javascript - 无法弄清楚为什么 opencv.js cv.fitEllipse() 会触发未捕获的异常与 1 个图像而不是另一个
- postgresql - 如何使用 typeorm 在 postgres 中保存 json 对象数组
- bash - 在 bash 脚本中使用命令行参数替换为脚本中的值
- r - 如何计算 DRPS(离散等级概率分数)