Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope in TypeScript/angularJS HTTP GET request

I'm new to typescript and angular.js and I'm struggling with a http get request. I'm using DefinitelyTyped for angular's type definitions.

My controller code looks like this:

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;
                }
            );
        }
    }

}

and my view like this:

<button ng-click="vm.doBet()">bet</button>
<div><span>bonus: {{ vm.bonus }}</span></div>

the view-model binding works fine, when I change the bonus variable without the http request. But when I try to update the bonus variable in the success function of the get request, I get following error:

TypeError: Cannot set property 'bonus' of undefined

How can I achieve to update variables in the success function?

I also would appreciate any suggestion, if there's a better/cleaner way or practice to update data on requests

like image 788
pichsenmeister Avatar asked Aug 15 '13 13:08

pichsenmeister


2 Answers

This can easily be done using TypeScript's lambda expression:

doBet() {
    this.http.get('http://localhost:9000/db').success(
        (data, status) => this.bonus = data
    );
}
like image 87
pichsenmeister Avatar answered Oct 10 '22 02:10

pichsenmeister


this in this.bonus = data; actually refers to the callback function inside success.

Instead you can do like this: $scope.vm.bonus = data;

like image 24
AlwaysALearner Avatar answered Oct 10 '22 00:10

AlwaysALearner