为什么 ngOnInit 被调用两次? [英] Why is ngOnInit called twice?

查看:44
本文介绍了为什么 ngOnInit 被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建新组件 ResultComponent,但它的 ngOnInit() 方法被调用了两次,我不知道为什么会发生这种情况.代码中,ResultComponent继承了父组件mcq-component@Input.

I trying to create new component, ResultComponent, but its ngOnInit() method is getting called twice and I don't know why this is happening. In the code, ResultComponent inherits @Input from the parent component mcq-component.

代码如下:

父组件(MCQComponent)

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'mcq-component',
    template: `
        <div *ngIf = 'isQuestionView'>
            .....
        </div>
        <result-comp *ngIf = '!isQuestionView' [answers] = 'ansArray'><result-comp>
    `,
    styles: [
        `
            ....
        `
    ],
    providers: [AppService],
    directives: [SelectableDirective, ResultComponent]
})
export class MCQComponent implements OnInit{
      private ansArray:Array<any> = [];
    ....
    constructor(private appService: AppService){}
    ....
}

<result-comp *ngIf = '!isQuestionView' [answers] = 'ansArray'><result-comp>`,样式: [`....`],提供者:[AppService],指令:[SelectableDirective, ResultComponent]})导出类 MCQComponent 实现 OnInit{私有 ansArray:Array= [];....构造函数(私有应用服务:AppService){}....}

Child Component (result-comp)

子组件(result-comp)

When run, console.log is showing up two times, the first time it shows the correct array but the second time it gives undefined. I've not been able to figure it out: why is ngOnInit in ResultComponent getting called twice? 

运行时,console.log 出现两次,第一次显示正确的数组,但第二次显示undefined.我一直无法弄清楚:为什么 ResultComponent 中的 ngOnInit 被调用两次?

解决方案

推荐答案

为什么要调用两次

<块引用>

现在,如果在检测组件的内容/视图子项的更改期间发生错误,ngOnInit 将被调用两次(见 DynamicChangeDetector).这可能会导致隐藏原始错误的后续错误.

Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). This can lead to follow up errors that hide the original error.

此信息来自此github issue

因此,您的错误似乎源于您代码中与此组件相关的其他地方.

So it seems that your mistake might have an origin elsewhere in your code, related to this component.

这篇关于为什么 ngOnInit 被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆