-1

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 ?

David
  • 4,332
  • 13
  • 54
  • 93
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards May 31 '20 at 10:37

1 Answers1

0

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

ruth
  • 29,535
  • 4
  • 30
  • 57