javascript - Typescript/Angular 2 问题

标签 javascript angularjs typescript angular

我是新手,甚至不确定我的问题是 Typescript 还是 Angular2 误解......

我有以下代码(减少到最少):

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);

在浏览器中转录并运行后,我在浏览器调试器中收到以下错误消息:

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

有人知道为什么“this”在这里未定义吗?我可以选择使用回调方法设置 {{foo}} 中的内容吗?

谢谢!

最佳答案

您需要使用箭头函数,以便能够使用词法 this 关键字:

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

有关箭头函数的词法 this 的更多提示,请参阅此链接:

关于javascript - Typescript/Angular 2 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36089762/

相关文章:

javascript - Kue作业完成后执行回调

javascript - angularjs中的确认对话框

reactjs - 类型 'Element | undefined' 不可分配给类型 'FC<any> | undefined'

javascript - 如何使 HostListener 用于滚动工作?

javascript - 如何将 Express 与 TypeScript 结合使用

javascript - 带有评论框的粘性页脚,如 WhatsApp

javascript - Vuejs 在 v-for 中使用函数

javascript - 使用 jquery 获取当前月份和日期

scala - Angularjs + OAuth + Play 2.0

javascript - 为什么angular的DI内联注解中的函数是数组元素?