angularjs - TypeScript/angularJS HTTP GET 请求中的范围

标签 angularjs typescript angularjs-scope

我是 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/

相关文章:

javascript - 带有 ng-repeat 的 Angular 切换表行 ng-class

javascript - 在组件/页面之间传递对象

javascript - 选择元素 Angular

javascript - 在 AngularJS 中返回范围变量的长度

javascript - 使用 Protractor 测试 Angularjs 警报

javascript - Angular 和 Animate.css - 一起使用时不会显示正确的信息

javascript - TypeScript 中闭包的 stub 函数

javascript - 使用 lodash 在数组列表中按字母排序名称

angularjs - Angular 服务将字符串作为字典返回

javascript - AngularJS 拼接模型