我是新手,甚至不确定我的问题是打字稿还是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
任何人都知道为什么&#34;这个&#34;这里未定义,我可以选择使用回调方法设置{{foo}}中的内容吗?
谢谢!
答案 0 :(得分:1)
您需要使用箭头功能,以便能够使用词汇this
关键字:
this.loadInput((input: string) => {
this.foo = input;
});
有关箭头函数词汇的更多提示,请参阅此链接: