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
This can easily be done using TypeScript's lambda expression:
doBet() {
this.http.get('http://localhost:9000/db').success(
(data, status) => this.bonus = data
);
}
this
in this.bonus = data;
actually refers to the callback function inside success
.
Instead you can do like this: $scope.vm.bonus = data;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With