[英]Init in constructor and logic/function in ngOnInit()
I have read on constructor
and ngOnInit
. 我已经阅读了constructor
和ngOnInit
。 And myself have came to a conclusion that we should make variable and service initialization in constructor
and any logic in ngOnInit
. 我得出一个结论,我们应该在constructor
函数中进行变量和服务初始化,并在ngOnInit
任何逻辑ngOnInit
。 And this seems clean to me. 这对我来说似乎很干净。
Here is my sample of implementation. 这是我的实现示例。 Hope to get some feedback if i am doing it right or i am understanding the constructor
and ngOnInit
wrongly. 如果我做得对,或者我错误地理解了constructor
和ngOnInit
希望能得到一些反馈。 Or should i just put everything on ngOnInit
instead. 还是我应该将所有内容放到ngOnInit
。
constructor(
public loading: LoadingController,
public auth: AuthService,
public data: DataService
) {
this.existingProfile = new EventEmitter<Profile>();
this.loader = this.loading.create({
content: 'Loading...'
});
}
ngOnInit() {
this.loader.present();
this.data.getProfile().subscribe(profile => {
this.userProfile = profile;
this.existingProfile.emit(this.userProfile);
this.loader.dismiss();
});
}
I've described the difference between constructor
and ngOnInit
in the article The essential difference between Constructor and ngOnInit in Angular in great details and this answer . 我已经在Angular中构造函数和ngOnInit之间的本质区别和该答案中详细描述了constructor
和ngOnInit
之间的区别。
If your initialization depends on the @Input
bindings then you have only one choice - ngOnInit
- since bindings are not available in the constructor. 如果您的初始化依赖于@Input
绑定,则只有一个选择ngOnInit
,因为绑定在构造函数中不可用。 If it's not dependent, then it's perfectly fine to perform initialization in the constructor. 如果不依赖,那么在构造函数中执行初始化就可以了。 In fact, if you use outputs then this: 实际上,如果使用输出,则此操作:
class O {
@Output ev = new EventEmitter();
is still compiled to 仍然编译为
class O {
constructor() {
this.ev = new EventEmitter();
However, the general recommendation is to use ngOnInit
for initialization. 但是,一般建议使用ngOnInit
进行初始化。 In this way everybody on your team knows to look inside ngOnInit
to understand how this component is initialized. 这样,您团队中的每个人都知道要查看ngOnInit
来了解如何初始化此组件。
So as you see it's a bit subjective if there's no dependency on ngOnInit
. 因此,如您所见,如果不依赖ngOnInit
则有点主观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.