Reputation: 6815
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
?
Upvotes: 0
Views: 256
Reputation: 214305
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:
Upvotes: 2