I'm a newbie and not even sure if my issue is a Typescript or Angular2 misunderstanding...

I have the following code (reduced to the minimum):

import {OnInit, Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
    selector: 'hello-app',
    template: `
        <h1>Foo:{{foo}}</h1>
    `
})
export class HelloApp implements OnInit {
    foo:  string;

    ngOnInit() {
      this.loadFoo();
    }

    loadFoo()
    {
      this.loadInput(function(input: string) {
        this.foo = input;
      })
    }

    ​loadInput (callback) {
        callback ("bar");
    }
}

bootstrap(HelloApp);

Once transcripted and ran in my browser I get the following error message in the browser debugger:

angular2.min.js:17 TypeError: Cannot set property 'foo' of undefined
    at hello.js:34
    at HelloApp.loadInput (hello.js:38)
    at HelloApp.loadFoo (hello.js:31)
    at HelloApp.ngOnInit (hello.js:28)
    at e.ChangeDetector_HostHelloApp_0.detectChangesInRecordsInternal (viewFactory_HostHelloApp:21)
    at e.detectChangesInRecords (angular2.min.js:6)
    at e.runDetectChanges (angular2.min.js:6)
    at e.detectChanges (angular2.min.js:6)
    at t.detectChanges (angular2.min.js:4)
    at angular2.min.js:9

Anyone know why "this" is undefined here and what's my option to set up what goes in {{foo}} using the callback method ?

Thanks !

share|improve this question
up vote 1 down vote accepted

You need to use an arrow function so you will be able to use the lexical this keyword:

this.loadInput((input: string) => {
    this.foo = input;
  });

See this link for more hints about the lexical this of arrow functions:

share|improve this answer
    
Awesome, I'm not sure to understand why, but that works ! Thanks ! – phil Mar 18 '16 at 16:48
1  
To understand it you must learn arrow function – micronyks Mar 18 '16 at 16:50
    
You're welcome! I added a link about how arrow functions work... The this keyword isn't managed the same way than callback functions. – Thierry Templier Mar 18 '16 at 16:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.