Is calling a function on ngOnInit async?

Felix picture Felix · Sep 14, 2016 · Viewed 27.5k times · Source

If I call a function in ngOnInit() that makes an observable call to get data, is the this.getSomething() call in ngOnInit still async or does ngOnInit wait until this.getSomething() returns a result? Basically does "doSomethingElse" get executed in ngOnInit() before or after this.getSomething() finishes?

ngOnInit() {
    this.getSomething();
    doSomethingElse;
}

getSomething() {
    this.someService.getData()
        .subscribe(
            result => {
                this.result = result;
            },
    error => this.errorMessage = <any>error);
}

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Sep 14, 2016

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(...)`
}