Issue with data not being assigned to TypeScript class variable

Utilizing an http call to fetch data from the backend, I am able to see the retrieved data in the browser console. However, for some reason, the data is not being assigned to the class variable as expected. The code snippet is shown below: "use strict";

export class EditTranslationsController {
    static IID: string = "EditTranslationsController";
    static $inject: string[] = ["$http", "$scope", "$log"];

    private _welcome : string = "HELLO WORLD!";
    public data : any;
    constructor(private $http: angular.IHttpService, 
                private $log: angular.ILogService,
                private $scope: angular.IScope) {

       this.sendUpdatedData();
    }

    public sendUpdatedData = () => {
        this.$http({
                    method : 'POST',
                    url : '/test'
            }).then(function successCallback(response) {
                console.log(response.data);
                this.data = response.data;
            }, function errorCallback(response) {
                this.$log.error(response);
            });
    }
}

While debugging the code, an error occurs at the line 'this.data=response.data'. The error message reads: TypeError: Cannot set property 'data' of undefined. I have been struggling to find a solution to this issue. Can anyone offer assistance?

Answer №1

It seems likely that the issue here is related to the value of 'this' within the function being passed to 'then', rather than referencing the class itself.

To address this, consider updating the code as follows:

.then((response) => 

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

Javascript operations for duplicating and altering arrays

In my Angular application, I am working with an array called subAgencies that is connected to a datasource. I need to implement 2-way binding on this array. Currently, I have a method in place where I copy the contents of the original array to a new one, ...

How can TypeScript associate enums with union types and determine the type of the returned object property?

I have a unique enum in conjunction with its corresponding union type. type User = { name: string, age: number } export enum StorageTypeNames { User = "user", Users = "referenceInfo", IsVisibleSearchPanel = "searchPane ...

Jest is unable to handle ESM local imports during resolution

I am encountering an issue with my Typescript project that contains two files, a.ts and b.ts. In a.ts, I have imported b.ts using the following syntax: import * from "./b.js" While this setup works smoothly with Typescript, Jest (using ts-jest) ...

What is the connection between <style>...</style> and angular material design, and how does it function together?

Take a look at this link. When you right-click on the words "Basic usage" (located at the top of the page, first block), you'll see the following HTML: <md-toolbar class="demo-toolbar md-primary"> <div class="md-toolbar-tools"> ...

Tips for receiving a linter/compiler warning when comparing a function without its call being made?

Often, I find myself making a common mistake when writing TypeScript code: class Foo { constructor() { } public get isFoo(): boolean { return true; } // getter public isBar(): boolean { return false; } // normal function } let foo = new Foo(); if ( ...

Issue with loading CSS in Angular 8 upon refreshing the page after building in production

Here is the structure of my index.html: <!doctype html> <html lang="hu"> <head> <meta charset="utf-8"> <title>WebsiteName</title> <base href="/"> <meta name="viewport& ...

Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve: create() { const map = this.make. ...

AngularJS 2 - error when trying to bind inner properties: ERROR: Unable to access property value due to undefined variable

I have been troubleshooting a problem with my AngularJS 2 app using Typescript. The issue arises when I attempt to access a property from the Typescript class in the HTML page using data binding. I have provided the relevant files below for reference. If t ...

Unable to cache new entry at the specified location (/Users/android/.gradle/7.5.1/checksums/sha1-checksums.bin) due to a java.io.IOException with the message "Bad file descriptor"

I encountered two errors when trying to run my React Native project. Issue 1: Failed to add entry '/Users/saadafridi/.gradle/.tmp/gradle_download14928641310389655157bin' to cache sha1-checksums.bin (/Users/saadafridi/Desktop/mobileapp/android/.g ...

Guide to setting up Cross-Origin Resource Sharing (CORS) for communication between your

We've been struggling to implement CORS for a few days with no luck. It would be really helpful to finally understand how to do this. Here is what we are trying to achieve: API server (partial configuration): // Configuration app.configure(functio ...

Exploring date comparisons in TypeScript and Angular 4

I'm currently working on a comparison of dates in typescript/angular 4. In my scenario, I've stored the system date in a variable called 'today' and the database date in a variable named 'dateToBeCheckOut'. My goal was to filt ...

The data being sent to the controller by my Service is not accessible in the expected manner

(function () { angular.module("app").controller('DashboardController', ['$q', 'dashboardService', function ($scope, $q,dashboardService) { var DashboardController = this; dashboardService.retrieveData(DashboardControll ...

What is the classification of the socket entity?

After searching through various posts, I couldn't find a solution to my problem so I decided to create my own thread. The issue I'm facing is determining the correct type for the 'socket' instance that I'm passing as a prop to my ...

What happens when Angular elements don't have an injector?

Exploring Angular's custom elements while steering clear of dependency injection is my current experiment. const MyElementElement = createCustomElement(MyElementComponent, { injector }); customElements.define('my-element', MyElementElement) ...

Error: useRef in TypeScript - cannot be assigned to LegacyRef<HTMLDivElement> type

Struggling to implement useRef in TypeScript and facing challenges. When using my RefObject, I need to access its property current like so: node.current. I've experimented with the following approaches: const node: RefObject<HTMLElement> = us ...

Click on a link to open it in the current tab with customized headers

In my Angular project, I am attempting to open a link by clicking a button that redirects to the specified URL using the following code: window.open(MY_LINK, "_self"); However, in this scenario, I also need to include an access token in the header when t ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

ESLint is notifying that the prop validation for ".map" is missing, with the error message "eslint react/prop-types" occurring in a Typescript React environment

Hey everyone, excited to be posting for the first time! Currently, I'm working on a small project using Typescript and React. I've run into an issue with ESLint where it doesn't recognize that a prop variable of type string[] should have a ...

Using Nested ng-repeat for Values and Keys in Angular

Struggling with implementing nested ng-repeats in my code. I have a JSON object with multiple layers and attempting to iterate through them to display the data. Here is the structure of the JSON: { "status": "success", "data": { "Mat": { "tota ...

Issues arise when trying to type ChangeEvent in React using Typescript

After spending some time learning React with TypeScript, I encountered a problem. The prop onChangeHandler in my code takes a function to modify properties in formik values. <Formik<FormModel> initialValues={{ favorite: ...