【问题标题】:Is calling a function on ngOnInit async?在 ngOnInit 上异步调用函数吗?
【发布时间】:2017-01-22 08:31:39
【问题描述】:

如果我在 ngOnInit() 中调用一个函数来进行可观察的调用以获取数据,那么 ngOnInit 中的 this.getSomething() 调用是否仍然是异步的,还是 ngOnInit 等到 this.getSomething() 返回结果?基本上是在 this.getSomething() 完成之前或之后在 ngOnInit() 中执行“doSomethingElse”吗?

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

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

【问题讨论】:

标签: angular asynchronous ngoninit


【解决方案1】:

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

例如你放在subscribe(...)里面的东西会在数据到达时执行。

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

有一些路由器生命周期钩子会等待返回的 Promise 或 observables,但组件或指令生命周期钩子都没有。

更新

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

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 中调用 this.getSomething() 之后有代码,那么该代码会在 getSomething() 中的代码完成后执行吗?
  • 不,它会(可能)在http 中的http 调用完成之前执行。
  • 谢谢各位,帮了大忙。我稍微更新了问题以澄清并在 ngOnInit 中添加了“doSomethingElse”行。基本上,正如@rinukkusu 所暗示的那样,我很想知道是否可以在 doSomething() 完成之前执行“doSomethingElse”(假设 doSomethingElse 与从 getSomething() 检索到的数据无关)所以应用程序不会等待服务调用完成。
  • getSomething() 被调用,this.someService.getData() 被调用(但立即返回,getSomething() 返回,doSomethingElse() 被执行,ngOnInit() 返回。然后最终服务器响应到达,result =&gt; { this.result = result}被执行(你可以看到你传递给subscribe 的内容,比如注册一个事件处理程序)。
猜你喜欢
  • 1970-01-01
  • 2020-11-07
  • 2020-01-17
  • 2019-06-13
  • 2020-12-13
  • 1970-01-01
  • 2014-06-14
  • 1970-01-01
  • 2019-08-18
相关资源
最近更新 更多