我试图创建新的组件,但它的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){}
....
}
Run Code Online (Sandbox Code Playgroud)
子组件(result-comp)
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector:'result-comp',
template: `
<h2>Result page:</h2>
` …Run Code Online (Sandbox Code Playgroud)由于某种原因,我的函数被调用两次,但我似乎不明白为什么。
我在这里看到这个问题
哪个引用了这个github问题
https://github.com/angular/angular/issues/6782
但这似乎表明我正在多个地方导入该文件,但我认为情况并非如此。
据我所知,我正在利用 Ionic 3 的延迟加载功能。
这是一个精简的 github 存储库的链接,您可以在本地运行来查看问题(很抱歉,我无法找出在 plunker 或 codepen 中运行它的最佳方法)
https://github.com/Jordan4jc/ionic-init-example
这个概念是主应用程序首先从商店加载一个令牌,然后验证它,如果它仍然是有效的路由,EventsPage但如果不是,它将路由到LoginPage
在此示例中,我伪造它并假装令牌有效并路由到EventsPage,正如您将在ngOnInit函数中看到的那样(如果我将其移动到构造函数theconsole.log 中,则事件会被调用两次。这将击中我的服务器获取最新数据,所以我真的不想两次调用我的 API。
编辑:这是内容app.component.ts
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import {Storage} from '@ionic/storage';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, storage: Storage) …Run Code Online (Sandbox Code Playgroud)