16

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);
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Felix
  • 610
  • 2
  • 9
  • 21

1 Answers1

24

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(...)`
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks Gunter. But if I have code after the this.getSomething() call in ngOnInit, does that code get executed AFTER the code in getSomething() finishes? – Felix Sep 14 '16 at 13:51
  • No, it will (probably) get executed before the `http` call in `getSomething` finishes. – Maximilian Riegler Sep 14 '16 at 13:52
  • Thanks guys, that helped. I updated the question a little to clarify and added the "doSomethingElse" line in ngOnInit. Basically, as @rinukkusu alluded to, I'm curious to know for sure if "doSomethingElse" can be executed before doSomething() finishes (assume doSomethingElse is unrelated to data retrieved from getSomething()) so the app isn't waiting around for the service call to finish. – Felix Sep 14 '16 at 14:45
  • 3
    `getSomething()` is called, `this.someService.getData()` is called (but returns immediately, `getSomething()` returns, `doSomethingElse()` is executed, `ngOnInit()` returns. Then eventually the server response arrives and `result => { this.result = result}` is executed (you can see what you pass to `subscribe` like registering an event handler). – Günter Zöchbauer Sep 14 '16 at 15:02