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

标签 javascript angular typescript scope ionic2

我正在使用 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}}

如何使 ctemplate.html 文件以及 mycomponent.ts 内的所有其他方法中可见?

最佳答案

使用箭头函数,例如:

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

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

还可以在此处查看有关词法 this 的更多详细信息:

关于javascript - 使变量在回调函数外部可见 - Ionic2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508221/

相关文章:

javascript - Yii 如何要求用户在 CStarRating 中确认他的选择

javascript - Raphael js 提高规模和翻译性能

javascript - 如何在 JavaScript 中执行不区分大小写的字符串排序数组?

Angular 4.3 - HttpClient 设置参数

javascript - 如何在 Angular 2 中包含外部 JavaScript 库?

angular - 编译错误: Calling function 'BreadcrumbModule' , function calls are not supported

typescript - 如何将类型绑定(bind)添加到 graphql 解析器映射

TypeScript 类如何定义非原型(prototype)类函数

angular - 无法获取事件路由参数

javascript - 对象字面量变量