angular.js:Typescript类构造函数"这是未定义的"

时间:2017-12-05 22:37:03

标签: javascript angularjs typescript angular-ui-router

我试图创建一个简单的TypeScript类,但是当它被实例化时,我在构造函数中收到this is undefined错误。

类别:

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);

1 个答案:

答案 0 :(得分:2)

  

为什么这不起作用?

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

修复

请勿使用角度为config的类。使用功能。

更多

相关问题