简体   繁体   English

打字稿/ Angular 2问题

[英]Typescript/Angular 2 issue

I'm a newbie and not even sure if my issue is a Typescript or Angular2 misunderstanding... 我是新手,甚至不确定我的问题是Typescript还是Angular2的误解...

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 ? 谁知道为什么这里没有定义“ this”,使用回调方法设置{{foo}}中的内容的选项是什么?

Thanks ! 谢谢 !

You need to use an arrow function so you will be able to use the lexical this keyword: 您需要使用箭头功能,以便可以使用词法this关键字:

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

See this link for more hints about the lexical this of arrow functions: 请参阅此链接,以获取有关箭头功能词汇this的更多提示:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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