Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions.

This is what my controller code looks like:

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 this is how my view is set up:

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

The view-model binding works properly when I change the bonus variable without the http request. However, when I attempt to update the bonus variable in the success function of the get request, I encounter the following error:

TypeError: Cannot set property 'bonus' of undefined

How can I successfully update variables in the success function? Any suggestions for a better or cleaner way to update data on requests would be greatly appreciated.

Answer №1

You can accomplish this task effortlessly by utilizing TypeScript's lambda syntax:

placeBet() {
    this.http.get('http://localhost:9000/api').success(
        (response, statusCode) => this.reward = response
    );
}

Answer №2

That in that.benefit = information; is actually pointing to the function inside completed.

Alternatively, you could use: $scope.app.benefit = info;

Answer №3

To access the $scope, you can include the method in the constructor 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;
        });
    }
}

If you need more guidance on using AngularJS with Typescript, check out this helpful tutorial.

Answer №4

Although I have yet to experiment with TypeScript, the issue at hand appears to be related to closures and scope. It seems that your success callback is executing asynchronously, causing the value of this to change inside it. To address this, consider 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;});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting up the Google Maps API within an Angular application without relying on any directives

Currently, I am attempting to integrate Google Maps into the application that I am developing. Utilizing the Places API for certain functionalities has been successful thus far. However, I have encountered an issue when trying to display a map on a specifi ...

Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value ...

Uploading a binary file and its corresponding name simultaneously using AngularJS and Flask

I am currently struggling with uploading a file and its filename simultaneously in an angular request, then receiving it in Flask to save on disk. The file is being read from the local disc using: reader.readAsArrayBuffer(importData.ruleFile.files[0]); T ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

Using AngularJS $resource with a JSON file for mocking data

My factory code looks like this: app.factory('AccordDepartement', function($resource, HttpCache) { return $resource('mocks/departements.json', {}, { query: { isArray: true, ...

The element is automatically assigned an 'any' type due to the fact that a 'string' expression cannot be utilized to index the type 'typeof'

I am facing an issue that I am having trouble understanding. The error message reads as follows: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof The proble ...

Issue encountered: [$injector:modulerr] while attempting to utilize the $modal functionality

I recently started exploring Angular and attempted to implement a modal window by following the guide at However, upon loading the page, I encountered the following error - Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/moduler ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

Tips for accurately defining the return type for querySelector(All) connections

I enjoy doing this particular task, ensuring the types are correct. const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null; const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>; While hovering over query ...

When a ListView item is clicked, a label will display text with text wrapping specific to the selected item in the list

Within the listview items, there is a label that should expand when clicked. For example, initially it only shows one line of text. Upon clicking on the label, it should expand to show 10 lines of text. Current Issue: At present, when I click on the firs ...

Is the Angular JS controller obtained through an AJAX call?

When I have an HTML file on the server with the ng-controller attribute: <div id="ng-app" ng-app="app"> <div ng-controller="AppController" nv-file-drop="" uploader="uploader"> </div> This file is fetched through an AJAX request ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

The comparison of Booleans in Typescript sometimes produces inaccurate results

There is a strange issue I encountered in one of my classes involving a readonly boolean property. Whenever I try to check this property, the results are not as expected. Here is an example of the code: // vorgang is a reference to the class, isEK is the ...

Using NodeJS API gateway to transfer image files to S3 storage

I have been attempting to upload an image file to S3 through API Gateway. The process involves a POST method where the body accepts the image file using form-data. I crafted the lambda function in TypeScript utilizing the lambda-multipart-parser. While it ...

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

What is the best way to create a generic variable and function that utilize the same type?

I am looking for a structure similar to interface propType { value: T action: (value: T) => void } The variable T can be any type, but it must be consistent for both value and action. Using any is not suitable as it could lead to a mismatch in ty ...

What is the best way to exclude React.js source files from a fresh Nest.js setup?

My setup includes a fresh Nest.js installation and a directory named "client" with a clean create-react-app installation inside. Here is the project structure: ./ ...some Nest.js folders... client <- React.js resides here ...some more Nest.js fo ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

validating if Object may be either 'null' or 'undefined'

In the code snippet below, I am attempting to verify whether hostel.country.address is null: return hostel.country.address && hostel.country.address.internalEmployeeIdentifier !== null || hostel.country.address.exter ...