簡體   English   中英

angular.js:Typescript類構造函數“這是未定義的”

[英]angular.js: Typescript class constructor “this is undefined”

我正在嘗試創建一個簡單的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);

為什么這不起作用?

因為你正在使用app.config([MyClass]); Angular會在沒有new情況下調用它,因此this將是未定義的

固定

不要使用帶有角度config類。 使用功能。

更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM