出于某种原因,我的函数被调用了两次,但我似乎无法弄清楚原因。
我在这里看到这个问题
引用了这个 github issue
https://github.com/angular/angular/issues/6782
但这似乎表明我在多个地方导入文件,但我认为情况并非如此。
据我所知,我正在利用 Ionic 3 的延迟加载。
这是一个精简的 github 存储库的链接,您可以在本地运行以查看问题(很抱歉,我想不出在 plunker 或 codepen 中运行它的最佳方法)
https://github.com/Jordan4jc/ionic-init-example
这个概念让主应用程序首先从商店中加载一个 token ,然后验证它是否仍然是通往 EventsPage
的有效路由,但如果不是,它将路由到 LoginPage
在这个例子中,我伪造了它并假装 token 有效并路由到 EventsPage
,正如您将在 ngOnInit
函数中看到的那样(如果我将其移至 Constructorconsole.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) {
platform.ready().then(() => {
storage.ready().then(()=>{
// pretend we loaded a JWT and verified it
this.rootPage = 'EventsPage';
});
splashScreen.hide();
});
}
}
最佳答案
我相信我已经找到了答案。
我在堆栈溢出上发现了这个问题
一个答案提到了模板编译错误,滚动浏览其余答案也提到了这样一个事实,即如果模板中存在一个按钮而没有明确的 type="button"
它可能会被处理作为浏览器的提交按钮,因此导致应用程序多次执行代码。将此属性添加到我在我的应用程序中发现的没有它的按钮似乎已经解决了这个问题。
关于angularjs - ngOnInit 和 Constructor 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039946/