javascript - Typescript:无法访问函数中的公共(public)变量

标签 javascript typescript

我想访问myVariable里面init()但变量是 undefined ,但我可以访问 convert() 内的变量。我在这里缺少什么建议吗?

export const MyComponent: ng.IComponentOptions = {
    templateUrl: 'MyView.html',
    bindings: {
        myVariable: '<',
    },
    controller: common.createController(MyController)
};

export class MyController {

    public myVariable: MyVariable;

    constructor($scope) {
        this.scope = $scope;
        this.init().then(() => {
            this.convert();
        });

        private init(): Promise<void> {
        console.log("init(): ", this.myVariable); //Error --> undefined
        //Call REST API and return a promise            
    }

    private convert(): void {
        console.log("convert(): ", this.myVariable); //No Error
    }
}

最佳答案

通常会发生这种情况,因为 init() 在基本构造函数之前被调用 - 基本构造函数通常是在 View 库中设置变量的。

我不知道你正在使用什么 View 库,但它看起来像 Angular 。在这种情况下,Angular 将在构造函数运行后设置绑定(bind)(它需要在分配绑定(bind)之前创建类,并且由于它不提供基类,因此无法在构造函数中利用基类进行绑定(bind))

Angular API 公开了类似于 React 的生命周期方法,您需要 $onInit 钩子(Hook),它将在构造函数和绑定(bind)完成后调用。

您可以在此处阅读更多信息https://docs.angularjs.org/guide/component

关于javascript - Typescript:无法访问函数中的公共(public)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338511/

相关文章:

javascript - 关于 package.json 中的 "scripts"键

C# Page_Load 中的 javascript 函数

javascript - 对 SQL 查询进行排队

javascript - Angular 类不是 Angular 模块

typescript - 有没有一种简单的方法来对 typescript 字典进行排序?

javascript - 如何在 typescript 中预先输入 React 元素数组

javascript - 谷歌地图问题 -> google.maps.KmlLayer

javascript - JW Player 准备就绪

angular - 使用 Angular + PrimeNG 在具有全局过滤器的表中延迟加载数据

javascript - 元素引用一个值,但在这里被用作类型