pichsenmeister
pichsenmeister

Reputation: 2132

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

Upvotes: 9

Views: 17469

Answers (4)

pichsenmeister
pichsenmeister

Reputation: 2132

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

doBet() {
    this.http.get('http://localhost:9000/db').success(
        (data, status) => this.bonus = data
    );
}

Upvotes: 10

0xc0de
0xc0de

Reputation: 8297

I haven't used typescript, but to me it looks like a closure/scope issue. Your success call back is running asynchronously so the value of this is different inside. Try binding the function call back with this.

this.http.get('http://localhost:9000/db').success(angular.bind(this,
    function(data: any, status: any) {this.bonus = data;});

Upvotes: 1

zs2020
zs2020

Reputation: 54532

You can put the method in the constructor in order to access the $scope like this:

constructor($scope: IGameScope, $http: ng.IHttpService, $location: ng.ILocationService) {
    $scope.vm = this;
    this.http = $http;

    $scope.doBet = function() {
        this.http.get('http://localhost:9000/db').success(function (data: any, status: any) {
            $scope.bonus = data;
        });
    }
}

Here is a tutorial about using AngularJS with Typescript.

Upvotes: 1

AlwaysALearner
AlwaysALearner

Reputation: 43947

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

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

Upvotes: 1

Related Questions