Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);                 }                ); 
like image 849
J King Avatar asked Nov 22 '15 05:11

J King


People also ask

How do I fix object is possibly undefined TypeScript?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

Why is this undefined TypeScript?

The value undefined means value is not assigned & you don't know its value. It is an unintentional absence of value. It means that a variable has been declared but has not yet been assigned a value.

What is the type of undefined in TypeScript?

TypeScript has two special types, null and undefined , that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type.

How do you use this in TypeScript?

The "this" keyword always points to the object that is calling a particular method. The type of "this" in an expression depends on the location in which the reference occurs: In a constructor, member function, or member accessor, this is of the class instance type of the containing class.


1 Answers

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) => {  }) 
like image 88
tymeJV Avatar answered Oct 01 '22 22:10

tymeJV