简体   繁体   中英

Typescript/Angular 2 issue

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 !

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM