angular.js:Typescript类构造函数“此未定义”

Dou*_*ell 5 javascript angularjs typescript angular-ui-router

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

类:

class MyClass {
    stuff: string;
    constructor(){
        this.stuff = 'stuff';
    }
}
app.config([MyClass]);
Run Code Online (Sandbox Code Playgroud)

编译成:

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

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

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

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

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

app.controller('mainController', MainController);
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 5

为什么这不起作用?

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

使固定

不要使用带有 angular 的类config。使用函数。

更多的