Is calling a function on ngOnInit async?
Asked Answered
N

1

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);
}
Nedra answered 14/9, 2016 at 13:42 Comment(1)
To wait, see hereRabon
M
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(...)`
}
Mannerly answered 14/9, 2016 at 13:46 Comment(4)
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?Nedra
No, it will (probably) get executed before the http call in getSomething finishes.Autotrophic
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.Nedra
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).Freberg

© 2022 - 2024 — McMap. All rights reserved.