我想访问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/