splunk splunk - 2 months ago 20
TypeScript Question

Make variable visible outside callback function - Ionic2

I'm working with ionic2 and inside

ngOnInit
method of my controller I have this:

ngOnInit()
{
let a;
this.myAsyncMethod(function(b)) // this is a callback of an async method defined somewhere before ngOnInit()
{
a = String(b);
}
}


I'd like to be able to pass variable
a
to my template and other methods inside the component file.

So I tried in this way:

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.
}

}


in my
template.html
I'd like to print
c
variable doing
{{c}}


How can I make
c
visible in both
template.html
file and in all other methods I have inside
mycomponent.ts
?

Answer

Use arrow function like:

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

This way this will refer to instance of your component.

See also more details about lexical this here: