angular.js: Typescript class 构造函数 "this is undefined"

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

我正在尝试制作一个简单的 TypeScript class,但是当它被实例化时,我在构造函数中收到一个 this is undefined 错误。

Class:

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

编译成:

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

为什么这不起作用?为什么 this 未定义?根据示例和我编写的其他代码,这似乎是合适的语法。

我的代码的其余部分(有效):

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

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

app.controller('mainController', MainController);

Why is this not working?

因为您正在使用 app.config([MyClass]); Angular 将在没有 new 的情况下调用它,因此 this 将是未定义的

修复

不要将 类 与 angular config 一起使用。使用函数。

更多