pic*_*ter 9 angularjs typescript angularjs-scope
我是typescript和angular.js的新手,我正在努力处理http get请求.我正在使用DefinitelyTyped进行角度的类型定义.
我的控制器代码如下所示:
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;
}
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的观点是这样的:
<button ng-click="vm.doBet()">bet</button>
<div><span>bonus: {{ vm.bonus }}</span></div>
Run Code Online (Sandbox Code Playgroud)
当我在没有http请求的情况下更改红利变量时,视图模型绑定工作正常.但是当我尝试更新get请求的success函数中的bonus变量时,我收到以下错误:
TypeError: Cannot set property 'bonus' of undefined
Run Code Online (Sandbox Code Playgroud)
如何在success函数中更新变量?
如果有更好/更清洁的方式或做法来更新请求数据,我也将不胜感激
pic*_*ter 10
这可以使用TypeScript的lambda表达式轻松完成:
doBet() {
this.http.get('http://localhost:9000/db').success(
(data, status) => this.bonus = data
);
}
Run Code Online (Sandbox Code Playgroud)