Search code examples
angularvariablesinitializationngoninit

Angular passing data to variable and that variable usage


Declaring variable

export class TestComponent implements OnInit {
testVar:string;

then initialising

ngOnInit() {

this.somefunction works.subscribe( 
this.testVar='testData';
console.log('log1 '+this.testVar);
);
console.log('log2 '+this.testVar);
}

now firing AfterViewInit:

ngAfterViewInit() {
console.log('log3 '+this.testVar);

The results are

log1 testData
log2 undefined
log3 undefined

question is why log2 and log 3 give undefined testVar and how can I fix that ?


Solution

  • That is not how asynchronous data works. The variables are not assigned values as soon the call is made. All statements that directly depend on an async data (this.testVar here) should be inside the subscription.

    ngOnInit() {
      this.service.someFunction().subscribe(
        value => {
          this.testVar='testData';
          console.log('log1 '+this.testVar);
          console.log('log2 '+this.testVar);
          ...
        }
      );
    }
    

    AfterViewInit lifecycle hook has nothing to do with how the variables are initialized in the controller. It will be called after Angular has fully initialized a component's view/template.

    See here for more details on how to access async data: https://stackoverflow.com/a/14220323/6513921