简体   繁体   English

构造函数中的Init和ngOnInit()中的逻辑/函数

[英]Init in constructor and logic/function in ngOnInit()

I have read on constructor and ngOnInit . 我已经阅读了constructorngOnInit 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. 如果我做得对,或者我错误地理解了constructorngOnInit希望能得到一些反馈。 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之间的本质区别该答案中详细描述了constructorngOnInit之间的区别。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM