我是 typescript 和 angular.js 的新手,我正在努力处理 http get 请求。 我正在使用 DefinitelyTyped用于 Angular 的类型定义。
我的 Controller 代码如下所示:
module game.Controller {
'use strict';
export interface IGameScope extends ng.IScope {
vm: GameCtrl;
}
export class GameCtrl {
private bonus: any;
private http: any;
constructor($scope: IGameScope, $http: ng.IHttpService, $location: ng.ILocationService) {
$scope.vm = this;
this.http = $http;
}
doBet() {
this.http.get('http://localhost:9000/db').success(function(data: any, status: any) {
this.bonus = data;
}
);
}
}
}
我的观点是这样的:
<button ng-click="vm.doBet()">bet</button>
<div><span>bonus: {{ vm.bonus }}</span></div>
当我在没有 http 请求的情况下更改 bonus 变量时, View 模型绑定(bind)工作正常。但是当我尝试在 get 请求的成功函数中更新 bonus 变量时,出现以下错误:
TypeError: Cannot set property 'bonus' of undefined
如何实现在成功函数中更新变量?
如果有更好/更清晰的方法或实践来更新请求数据,我也将不胜感激
最佳答案
这可以使用 TypeScript 的 lambda 表达式轻松完成:
doBet() {
this.http.get('http://localhost:9000/db').success(
(data, status) => this.bonus = data
);
}
关于angularjs - TypeScript/angularJS HTTP GET 请求中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18253306/