是否在ngOnInit异步上调用函数? [英] Is calling a function on ngOnInit async?

查看:254
本文介绍了是否在ngOnInit异步上调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在ngOnInit()中调用一个可观察的调用来获取数据的函数,则ngOnInit中的this.getSomething()调用是否仍是异步的?或者ngOnInit是否等待,直到this.getSomething()返回结果?基本上是在this.getSomething()完成之前或之后在ngOnInit()中执行"doSomethingElse"吗?

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

推荐答案

ngOnInit()本身并不等待异步调用. 您可以自己链接代码,使其仅在异步调用完成时执行.

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.

例如,当数据到达时,将执行放置在subscribe(...)中的内容.

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

subscribe(...)之后的代码将立即执行(在异步调用完成之前).

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

有一些路由器生命周期挂钩等待返回的promise或observable,但没有组件或指令生命周期挂钩.

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

更新

为确保在getData()完成后执行this.getSomething()之后的代码,请将代码更改为

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

这篇关于是否在ngOnInit异步上调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆