在onInit生命周期钩子上调用异步函数时无法正常工作 [英] Async function not working as intended when called at onInit lifecycle hook

查看:123
本文介绍了在onInit生命周期钩子上调用异步函数时无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有一个应该在启动应用程序时加载本地数据库的服务。为此,使用函数 GetData()。我尝试通过调用 ngOnInit()生命周期钩子来使用它。它将结果记录在控制台中,但属性 datum 似乎没有变化。

In my project I have a service that should load local database when the app is started. For that the function GetData() is used. I try to use it by calling at the ngOnInit() lifecycle hook. It logs the result in the console, but the property datum appears to be unchanged.

但是,如果我添加 GetData()按钮的方法,属性更改,数据按预期显示在控制台中。

However, if I add GetData() method to a button, the property changes and data is displayed in the console as intended.

我查看的所有来源都表明,如果我需要,加载数据库的正确方法是使用 ngOnInit() hook,这就是为什么当我发起来自DOM的某些事件时,我不打算调用 GetData()

All sources that I looked through suggest that the right way to load the DB if I need it right away is to use ngOnInit() hook, that's why I don't wat to call GetData() when some event from the DOM is fired.

组件

export class AppComponent implements OnInit {
  datum;
  constructor(private searchService: SearchService){ }
  getData(){
    this.searchService.getData().subscribe(
      data => {
        this.datum = data[0];
        console.log(this.datum);},
      err => console.log("E", err)
    );
  }

  ngOnInit(){
    this.getData();
  }
  title = 'app';
}

HTML

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
    Data: {{datum | json}}
  </h1>
  <button (click)="getData()">Click Me</button>

已加载应用

点击按钮

编辑
getData()与 setTimeout()按照AlexKhymenko的建议

EDIT Implementation of getData() with setTimeout() as suggested by AlexKhymenko

  getData(){
    this.searchService.getData().subscribe(
      data => {
        setTimeout(() =>{
          this.datum = data[0];
        });
        console.log(this.datum);},
      err => console.log("E", err)
    );
  }


推荐答案

你需要做的是例如通过调用setTimeout手动运行更改检测。我创建了一个Plunker

What you need to do is to run change Detection manually for example by calling setTimeout. I have created a Plunker.

export class AppComponent implements OnInit {
  datum;
  title = 'app';

  constructor(private searchService: SearchService){ }
       }

 ngOnInit(){
   this.getData();
 }
  getData(){
      this.searchService.getData().subscribe(
  data => {
   setTimeout(() => {
            this.datum = data[0];
   })
    console.log(this.datum);},
  err => console.log("E", err)
);

}

这篇关于在onInit生命周期钩子上调用异步函数时无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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