J King
J King

Reputation: 4434

why "this" is undefined in typescript module with http promise

this is my first typescript and angular attempt and I am stuck on one problem.

I have a module controller defined in the following way (.ts file):

module app.controllers {
    "use strict"

    import services = app.services;

    export class calendarController {

        calBlock: any;
        deptId: number;
        calSvc: app.services.calendarService;

        static $inject = ["$scope", "calendarService"];

        constructor(isolateScope: directives.calendarScope, calSvc: services.calendarService) {

            this.deptId = isolateScope.deptId;
            this.calSvc = calSvc;

            calSvc.getMonthBlock(12, 2015, 1, this.deptId)
            .then(
                function (response) {
                    //promise fullfilled (regardless of outcome)                
                    this.calBlock = response.data;
                 },
                 function (error) {
                //handle errors
                    alert(error);
                 }   
             );
        }
    }
}

Here is the service this controller is dependant on:

module app.services {
    "use strict"
    export class calendarService {

        private _http: ng.IHttpService;

        static $inject = ["$http"];

        constructor(http: ng.IHttpService) {
            this._http = http;            
        }

        getMonthBlock = function (month:number, year:number, calId:number, deptId:number) {

            //initialise service url
            var sURL = _sf.getServiceRoot('KrisisShifts') + "CalendarService/GetMonthCal/" + calId + "/" + deptId + "/" + month + "/" + year;
            //create config object for get function
            var config = {
                URL: sURL,
                method: "GET",
                dataType: 'json',
                headers: {
                    'ModuleId': _sf.getModuleId(),
                    'TabId': _sf.getTabId(),
                    'RequestVerificationToken': _sf.getAntiForgeryValue()
                }
            }
            //return the promise of the http.get function
            return this._http.get(sURL, config);

        }
    }
}

The problem occurs on the following line of the controller module:

this.calBlock = response.data;

The problem is that THIS is undefined so therefore calBlock is also undefined and the jsConsole throws an error:

TypeError: Cannot set property 'calBlock' of undefined at shift-calendar-controller.js?cdv=28:14

I am relativly new to javascript and angular and typescript so I am having trouble figuring out why "this" is undefined. I think its because its enclosed in a function.

I need a way to assign the reponse.data (a json array from a $http call) to the calBlock property of the typescript class for my controller. Can someone help me understand why this is undefined within the response function and how I can access it?

Thanks

EDIT: SOLUTION BASED ON tymeJV's answer

here is the re-written calBlock call:

            calSvc.getMonthBlock(12, 2015, 1, this.deptId)
            .then((response) => {
                    //promise fullfilled (regardless of outcome)                
                    this.calBlock = response.data;
                },
            (error) => {
                    //handle errors
                    alert(error);
                }   
            );

Upvotes: 33

Views: 31227

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Because the context of this is lost in the callback. Use arrow functions in typescript to preserve the context!

calSvc.getMonthBlock(12, 2015, 1, this.deptId).then((response) => {

})

Upvotes: 72

Related Questions