Jordan
Jordan

Reputation: 2523

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

why ngOnInit called twice?

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.

As far as I know I'm taking advantage of Ionic 3's lazy loading.

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

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

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 Constructortheconsole.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.

EDIT: This is the content in the 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();
    });
  }
}

Upvotes: 4

Views: 11723

Answers (1)

Jordan
Jordan

Reputation: 2523

I believe I have found the answer.

I found this question on stack overflow

why ngOnInit called twice?

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.

Upvotes: 5

Related Questions