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

查看:518
本文介绍了为什么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){}
    ....
}

子组件(结果比较)

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

@Component({
    selector:'result-comp',
    template: `
        <h2>Result page:</h2>

    `
})
export class ResultComponent implements OnInit{
    @Input('answers') ans:Array<any>;

    ngOnInit(){
        console.log('Ans array: '+this.ans);
    }
}

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

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?

推荐答案

为什么两次被调用

现在,如果在检测组件的内容/视图子项的更改期间发生错误,则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问题

因此,您的错误似乎可能与该组件相关,而在代码的其他地方起源.

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

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

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