使变量在回调函数外部可见 - Ionic2

Make variable visible outside callback function - Ionic2

我正在使用 ionic2 和我控制器的 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}}

如何使 ctemplate.html 文件和我在 mycomponent.ts 中的所有其他方法中都可见?

像这样使用箭头函数:

this.myAsyncMethod((b) => {
  this.c = String(b);
});

这样 this 将引用您的组件实例。

另请参阅此处有关词法 this 的更多详细信息: