打字稿/角度 2 问题
Typescript/Angular 2 issue
我是新手,甚至不确定我的问题是否是打字稿或 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 的更多提示,请参阅此链接:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。
相关文章:
- 尝试将服务链接到控制器时出现角度问题
- 在有角度的ui网格中设置动态列的问题
- ng include导致角度问题
- 无法运行php代码,有角度路由问题
- 控制器中有手表时出现角度UT问题
- 绑定的角度ng-max问题
- 角度在60多分钟内路线问题
- $scope和$routeParams的角度问题
- 角度指令性能问题
- 离子/角度$urlRouterProvider.otherwise问题
- 有UI路由问题的角度路由
- 角度资源注入的问题
- CORS问题,同时提交数据到谷歌表单的角度
- 为了在列表中搜索,角度过滤器有问题
- 嵌套ng包含的角度问题
- 角度路线弓下载问题
- 单元测试窗口位置分配的角度问题
- 有角度的seo友好URL和页面重新加载问题
- 在DOM(html)上下文中使用角度作用域函数时出现的问题
- 角度:多个 ng 假设问题