加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

有角度 – 为什么ngOnInit叫两次?

发布时间:2020-12-17 08:04:27 所属栏目:安全 来源:网络整理
导读:我试图创建新的组件,但其ngOnInit()方法被调用两次,我不知道为什么会发生这种情况?这里我创建了一个名为ResultComponent的组件,该组件从称为mcq-component的父组件接受@Input 这是代码: 父组件(MCQComponent) import { Component,OnInit } from '@angul
我试图创建新的组件,但其ngOnInit()方法被调用两次,我不知道为什么会发生这种情况?这里我创建了一个名为ResultComponent的组件,该组件从称为mcq-component的父组件接受@Input
这是代码:

父组件(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)

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);
	}
}

这里的控制台日志显示2次:第一次它显示正确的数组,但第二次它显示未定义,但我无法弄清楚,为什么ngOnInit从ResultComponent得到调用两次?

为什么叫两次

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

所以似乎你的错误可能在你的代码的其他地方,与这个组件有关。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读