我正在使用 ionic2 并在 Controller 的 ngOnInit
方法中使用:
ngOnInit()
{
let a;
this.myAsyncMethod(function(b)) // this is a callback of an async method defined somewhere before ngOnInit()
{
a = String(b);
}
}
我希望能够将变量 a
传递给我的模板和组件文件内的其他方法。
所以我尝试了这种方式:
export class myComponent {
c:string;
constructor(....){ // some stuff }
... other methods
ngOnInit()
{
let a;
this.myAsyncMethod(function(b))
{
a = String(b);
this.c = a; // here I get this error in red: EXCEPTION: TypeError: Cannot set property 'c' of undefined
}
// if I would put this.c = a here I'll get `c` undefined because I'd be outside the callback function and `a` is not defined yet.
}
}
在我的template.html
中,我想打印c
变量执行{{c}}
如何使 c
在 template.html
文件以及 mycomponent.ts
内的所有其他方法中可见?
最佳答案
使用箭头函数,例如:
this.myAsyncMethod((b) => {
this.c = String(b);
});
这样 this
将引用您的组件的实例。
还可以在此处查看有关词法 this
的更多详细信息:
关于javascript - 使变量在回调函数外部可见 - Ionic2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508221/