david
david

Reputation: 115

Typescript: unable to access public variable in a function

I want to access myVariable inside init() but the variable is undefined, but I am able to access the variable inside convert(). Any suggestions what I am missing here?

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
    }
}

Upvotes: 1

Views: 1370

Answers (1)

caesay
caesay

Reputation: 17233

Generally this happens because init() is being called before the base constructor - the base constructor is usually what sets the variable in view libraies.

I don't know what view library you're using but it looks like angular. In this case, angular will set the binding after your constructor runs (it needs to create the class before it can assign the binding, and since it doesn't provide a base class it can't utilize that for binding in the constructor)

The Angular API exposes life-cycle methods similar to react, you need the $onInit hook which will be called after the constructor and binding has finished.

You can read more here https://docs.angularjs.org/guide/component

Upvotes: 1

Related Questions