ngOnInit 和 Constructor 被调用两次 [英] ngOnInit and Constructor are called twice
问题描述
由于某种原因,我的函数被调用了两次,但我似乎无法弄清楚原因.
For some reason I'm getting the function being called twice and I can't seem to figure out why.
我在这里看到了这个问题
I see this question here
引用了这个 github 问题
Which references this github issue
https://github.com/angular/angular/issues/6782
但这似乎表明我在多个地方导入文件,但我不认为是这种情况.
But that would seem to suggest I'm importing the file in multiple places which I don't believe is the case.
据我所知,我正在利用 Ionic 3 的延迟加载.
As far as I know I'm taking advantage of Ionic 3's lazy loading.
这是一个精简的 github 存储库的链接,您可以在本地运行以查看问题(很抱歉,我无法找到在 plunker 或 codepen 中运行的最佳方法)
Here is a link to a stripped down github repo you can run locally to see the issue (I'm sorry I can't figure out the best way to get this to run in plunker or codepen)
https://github.com/Jordan4jc/ionic-init-example
这个概念让主应用程序首先从商店中加载一个令牌,然后验证它,如果它仍然是到 EventsPage
的有效路由,但如果不是,它将路由到 LoginPage
The concept has the main app first load a token out of the store, then verify it and if it's still valid route to the EventsPage
but if it's not it would route to a LoginPage
在本例中,我伪造它并假装令牌有效并路由到 EventsPage
,正如您将在 ngOnInit
函数中看到的那样(如果我将它移到构造函数中console.log` 会被调用两次.这将访问我的服务器以获取最新数据,所以我真的不想两次访问我的 API.
In this example I fake it and just pretend the token is valid and route to the EventsPage
, as you'll see in the ngOnInit
function (and event if I move it into the Constructorthe
console.log` gets called twice. This will be hitting my server to get the latest data so I really don't want to hit my API twice.
这是 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();
});
}
}
推荐答案
相信我已经找到了答案.
I believe I have found the answer.
我在堆栈溢出时发现了这个问题
I found this question on stack overflow
一个答案引用了模板编译错误,并且滚动浏览其余答案还引用了这样一个事实,即如果您的模板中存在一个按钮而没有明确的 type="button"
它可能会被处理作为浏览器的提交按钮,因此会导致应用程序多次执行代码.将此属性添加到我在我的应用程序中找到但没有它的按钮似乎已经解决了这个问题.
One answer referenced a template compilation error, and scrolling through the remaining answers one also references the fact that if a button is present in your template without an explicit type="button"
it may be treated as a submit button by your browser and therefore cause the app to execute the code multiple times. Adding this attribute to the buttons I found in my app that did not have it appears to have solved the issue.
这篇关于ngOnInit 和 Constructor 被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!