【问题标题】:ngOnInit called many times in all inheritance classes in Angular 5ngOnInit 在 Angular 5 的所有继承类中多次调用
【发布时间】:2018-12-19 02:58:09
【问题描述】:

我使用 import {Ng2StateDeclaration} from '@uirouter/angular'; 我现在在 Angular 5 中遇到了一个问题 我有没有模板的 Paper 类:

export class Paper implements OnInit {
  ngOnInit(): void {
     // async function here
     this.loadData();
   }

}

现在我有了另一个名为 PaperEdit 的类:

export class PaperEdit extends Paper{
  constructor(){super();}
}

在 PaperEdit 类中,我有很多带有长 html 的部分: paper-edit.html

<paper-edit-form-1></paper-edit-form-1>
<paper-edit-form-2></paper-edit-form-2>
<paper-edit-form-3></paper-edit-form-3>

PaperEditForm1,2,3是一个只有html文件的类,没有逻辑,我想继承Paper类的所有变量和函数,比如PaperEdit

export class PaperEditForm1 extends Paper {
  constructor(){super();}
  // no function here`

}

结果是:Paper 类的 ngOnInit 运行了 4 次,这意味着 this.loadData() 也运行了 4 次。 因此,任何防止此问题的方法,我希望该生命周期只运行 1 次!谢谢。

【问题讨论】:

  • 你不能让 4 个组件的生命周期只运行一次。所以这个问题没有意义。
  • @cgTag:是的。我正在使用import {Ng2StateDeclaration} from '@uirouter/angular';。这意味着在 url:edit/view 页面中,我将首先加载 Paper 组件。该组件的样式为空。如果在 url: '/edit+ id' 中,我将加载 PaperEdit 组件
  • 我看不出您的问题与路由有何关系?

标签: angular class inheritance duplicates


【解决方案1】:

我遇到过类似的问题。不要在 PaperEditForm1 类中继承 Paper 类,只需将函数 loadData 静态。在子 PaperEditForm1 类中导入 Paper 类。现在,只需调用使用 Paper.loadData() 的 loadData 静态函数。这可以最大限度地减少构造函数调用并删除继承。它仅在需要时调用。这解决了我的情况。

【讨论】:

  • 感谢您的好主意。但是我有很多 PaperEditForm 类,所以我会在这里在 3 个子类中调用 Paper.loadData() 3 次吗?
  • 是的,您需要在需要继承功能的每个类中编写 Paper.loadData()。这可能会增加代码长度,但也可以简洁地提高性能。
  • 谢谢,我按照你的方法解决了问题:)
猜你喜欢
  • 1970-01-01
  • 2017-12-10
  • 2018-12-14
  • 2018-12-08
  • 2017-02-20
  • 2015-07-29
  • 1970-01-01
  • 2014-08-06
  • 1970-01-01
相关资源
最近更新 更多