12

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);
}
4

1 回答 1

22

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(...)`
}
于 2016-09-14T13:46:50.970 回答