【问题标题】:Angular 5 will not run more than one method on ngOnInit?Angular 5 不会在 ngOnInit 上运行不止一种方法?
【发布时间】:2018-01-30 05:50:59
【问题描述】:

我附上了我正在尝试做的截图。这是如此基本但如此令人沮丧。从调用的第一个方法中检索对象数组后,我必须运行数据解析,但我无法将我的方法添加到 ngOnInit 内部的方法或直接在 ngOnInit 内部的方法之后。无论哪种方式,该方法都无法运行。有任何想法吗? Image

  ngOnInit() {
    this.getSiteContent(this.route.snapshot.params['id']);

    //Doesnt work
    this.addUpdatedPages();
  }

//in use
getSiteContent(id) {

    this.http.get('/site-content/'+id).subscribe(data => {
      this.siteContent = data;

    });

    //Doesn't show..
    console.log('End of getSiteContent');

}

addUpdatedPages(){

  //Doesn't show
  console.log('Adding pages...');

  for (var i = 0; i < this.siteContent.length; i++) {

    this.checkNull(this.siteContent[i].SiteID, this.siteContent[i].SitePageID);
    console.log(this.nullCheck[0].SiteID);

    if (this.nullCheck.length > 0) {
      this.siteContent[i].SitePageContent = this.nullCheck[0].SitePageContent;
    }

} 
}

【问题讨论】:

  • 确保getSiteContent 方法没有停止。你验证过这个吗?它是否在做一些需要很长时间并且是同步的,这使它在调用任何其他代码之前等待? ngOnInit 没有理由只调用一个函数……它必须走到该函数的末尾并返回以继续执行任何其他代码,因为 JavaScript 是同步的并且只使用一个执行过程。
  • 尝试两件事。首先从函数中删除数字,所以只需 this.test()。也只需尝试 console.log("test") 而不是警报,因为它们并不总是可靠的。除此之外,我看不出还有什么问题。
  • 请将代码发布为文本,而不是图像。
  • getSiteContent 需要一点时间来加载,但是当它完成后,我可以修改数据,但是我想从我的表单中修改数据。我正在尝试在它到达表单之前对其进行修改。
  • 在第一个被调用的方法中添加了 console.log 来代替我添加的方法,并且消息不会显示在控制台中。即使它抓取了数据,该方法也可能由于某种原因挂起?

标签: node.js angular


【解决方案1】:

当您调用this.http.get 时,一切都指向一个未处理的异常。你应该检查你的浏览器控制台,如果有的话就会显示出来。一个可能的原因是http 未被注入或未定义。

ngOnInit() {
    this.getSiteContent(this.route.snapshot.params['id']);

    // if the above throws an exception anything below would not be called
    this.addUpdatedPages();
}

getSiteContent(id) {
    this.http.get('/site-content/'+id).subscribe(data => {
      this.siteContent = data;
    });

    // If the call above to this.http.get throws an exception the code below would not be called
    console.log('End of getSiteContent');
}

话虽如此,应该在http.getsubscribe 中调用方法addUpdatedPages,因为您希望它在检索数据库之后发生。修改 getSiteContent 以便将行移到 observable 的 subscribe 调用的回调中。

this.http.get('/site-content/'+id).subscribe(data => {
  this.siteContent = data;
  this.addUpdatedPages();
});

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 2017-10-24
    • 2019-01-27
    • 2013-11-23
    • 2019-09-13
    • 2018-02-27
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多