我应该在Angular中再次调用ngOnInit()吗?

vib*_*97a 2 typescript angular

我是Angular的新手,这个问题可能听起来很愚蠢.请多多包涵.

我定义了我的ngOnInit喜欢:

ngOnInit() {
 this.rowData = this.studentService.getStudents();//Make http calls to populate data
}
Run Code Online (Sandbox Code Playgroud)

在一个事件中,我再次调用ngOnInit,因为我需要重新加载数据:

onSomeEvent(){
 this.ngOnInit();
}
Run Code Online (Sandbox Code Playgroud)

这个可以吗?或者我应该写一行来再次调用http,如果这ngOnInit()是一个昂贵的方法.

Par*_*ain 9

不,这不是一个好习惯.

更好的方法是从ngOnInit需要时调用某些方法并重新调用相同的方法.像这样-

ngOnInit() {
 this.onLoad();
}

onLoad() {
this.rowData = this.studentService.getStudents();//Make http calls to populate data
}

onSomeEvent(){
 this.onLoad();
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你自己打电话,不是 但它使代码的可读性降低.ngOnInit有一个目的,INITIALISING组件.将它用于其他东西(在你的情况下,你的目的是"getListOfStudents")使代码难以理解.其他开发人员不会期望多次调用ngOnInit.小代码库中的简单问题.代码增长时的大问题.因此,拥有一个方法"getListOfStudents"并从ngOnInit()调用该方法将是一个好习惯. (3认同)