Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js: Typescript class constructor "this is undefined"

I'm trying to make a simple TypeScript class, however when it's instantiated I receive an this is undefined error in the constructor.

Class:

class MyClass {
    stuff: string;
    constructor(){
        this.stuff = 'stuff';
    }
}
app.config([MyClass]);

Gets compiled into:

var MyClass = /** @class */ (function () {
    function MyClass() {
        this.stuff = 'stuff';
    }
    return MyClass;
}());
app_module_1.app.config([MyClass]);

Why is this not working? Why is this undefined? This seems to be the appropriate syntax based on examples and other code I've written.

The remainder of my code (this works):

export let app = angular.module('timeApp', [
    uirouter
]);

class MainController{
    stuff: string;
    constructor(){
        this.stuff = "TESTING";
    }
}

app.controller('mainController', MainController);
like image 876
Douglas Gaskell Avatar asked Dec 05 '17 22:12

Douglas Gaskell


1 Answers

Why is this not working?

Because you are using app.config([MyClass]); Angular will call it without new and hence this will be undefined

Fix

Don't use classes with angular config. Use functions.

More

  • new : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
like image 162
basarat Avatar answered Oct 19 '22 10:10

basarat