Vibs
Vibs

Reputation: 357

Typescript: data not getting assigned to class variable

I am using http call to get the data from back end. I can see the data coming back from backend as it gets logged into the browser console. But the data is not getting assigned to the class variable. Below is my code- "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);
            });
    }
}

So if I debug my code, I can see a error at line 'this.data=response.data'. error is-TypeError: Cannot set property 'data' of undefined. I am not getting the solution for this problem. Can somebody please help?

Upvotes: 1

Views: 112

Answers (1)

Mike Hanson
Mike Hanson

Reputation: 306

I suspect this is due to what 'this' actually represents inside the function passed to 'then'. It is not referencing the class.

Try changing:

.then(function successCallback(response)

to

.then((response) => 

Upvotes: 3

Related Questions