Is calling a function on ngOnInit async? Is calling a function on ngOnInit async? angular angular

Is calling a function on ngOnInit async?


ngOnInit() on itself doesn't wait for async calls.You can yourself chain code the way that it only executes when the async call is completed.

For example what you put inside subscribe(...) is executed when data arrives.

Code that comes after subscribe(...) is executed immediately (before the async call was completed).

There are some router lifecycle hooks that wait for returned promises or observables but none of the component or directive lifecycle hooks does.

update

To ensure code after this.getSomething() is executed when getData() is completed change the code to

ngOnInit() {    this.getSomething()    .subscribe(result => {      // code to execute after the response arrived comes here    });}getSomething() {    return this.someService.getData() // add `return`        .map( // change to `map`            result => {                this.result = result;            },  //  error => this.errorMessage = <any>error); // doesn't work with `map`   // (could be added to `catch(...)`}