0

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?

1
  • let self = this; then inside the method self.c = a Commented Sep 15, 2016 at 10:15

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.