0

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 !

1 Answer 1

1

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:

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

3 Comments

Awesome, I'm not sure to understand why, but that works ! Thanks !
To understand it you must learn arrow function
You're welcome! I added a link about how arrow functions work... The this keyword isn't managed the same way than callback functions.

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.