After use --prod code not work


#1

This code not work after use --prod to build:

"this.platform.registerBackButtonAction(() => { … }

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, ToastController, App, IonicApp, MenuController, AlertController} from 'ionic-angular';
import { StatusBar, Splashscreen, SQLite } from 'ionic-native';

import { HomePage } from '../pages/home/home';
import { OrcamentoPage } from '../pages/orcamento/orcamento';
import { CarrinhoPage } from '../pages/carrinho/carrinho';
import { ConfigPage } from '../pages/config/config';
import { ConfigServidorPage } from '../pages/configservidor/configservidor';
import { PreferenciasPage } from '../pages/preferencias/preferencias';
import { ModalProdutosPage } from '../pages/modalprodutos/modalprodutos';
import { EditarServidorPage } from '../pages/editarservidor/editarservidor';
import { TestePage } from '../pages/teste/teste';
import { Database } from '../providers/database';
import { Webservice } from '../providers/webservice';
import { AppMinimize } from '@ionic-native/app-minimize';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild('nav') nav: Nav;
  rootPage: any = HomePage;
  private storage: SQLite;
  private isOpen: boolean;
  pages: Array<{title: string, component: any}>;
  public usuario: any;
  public token: any;

  constructor(public platform: Platform, public toastCtrl: ToastController, public webservice: Webservice, 
  public appCtrl: App, public ionicApp: IonicApp, public menuCtrl: MenuController, public alertCtrl: AlertController, 
  public database: Database, public appMinimize: AppMinimize) {
    this.initializeApp();

    // Menu
    this.pages = [
    { title: 'Dashboard', component: OrcamentoPage },
    { title: 'Carrinho', component: CarrinhoPage },
    { title: 'Sair', component: HomePage }
    ];
  }

  initializeApp() {
    this.platform.ready().then(() => {
      if(!this.isOpen) {
        
        this.storage = new SQLite();
        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {
            this.storage.executeSql("CREATE TABLE IF NOT EXISTS configDB(id INTEGER PRIMARY KEY AUTOINCREMENT, descricao VARCHAR, loja VARCHAR, servidor VARCHAR, token VARCHAR, itens VARCHAR, buscapadrao VARCHAR, power VARCHAR)", {})
            .then(
              (data) => {
                console.log("tabela criada com sucesso");
              }, 
              (error) => { 
                this.presentToast(JSON.stringify(error));
              })
          },
          (error) => {
            this.presentToast("Erro ao abrir banco de dados " + error);
        });

        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(() => {
          this.storage.executeSql("CREATE TABLE IF NOT EXISTS carrinho(codigo VARCHAR, item VARCHAR, valorvenda VARCHAR, valortotal VARCHAR, estoque VARCHAR, quantidade VARCHAR)", {})
          .then(
            (data) => { 
              console.log("Tabela criada com sucesso: " + data);
            }, 
            (error) => { 
              this.presentToast("Não foi possível criar a tabela: CARRINHO " + error);
              
            });
        },
        (error) => {
          this.presentToast("Erro ao abrir banco de dados " + error);
        });

        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {
            this.storage.executeSql("CREATE TABLE IF NOT EXISTS usuarioapp(codigo VARCHAR, cripto_pre_cma VARCHAR, cripto_pre_sugerido VARCHAR, cripto_loja VARCHAR)", {})
            .then(
              (data) => {
                console.log("Tabela criada com sucesso: usuarioapp" + data);
              }, 
              (error) => { 
                this.presentToast("Não foi possível criar a tabela: USUARIOAPP " + error);
              });
          },
          (error) => {
            this.presentToast("Erro ao abrir banco de dados " + error);
          });

        this.storage.openDatabase({name: "infosysDB.db", location: "default"})
        .then(
          (data) => {
            this.storage.executeSql("CREATE TABLE IF NOT EXISTS preferencias(tipo VARCHAR, cliente VARCHAR, codigo VARCHAR, tipodepreco VARCHAR, tabeladepreco VARCHAR, tabelacodigo VARCHAR)", {})
            .then(
              (data) => {
                console.log("Tabela criada com sucesso: preferencias" + data);
              }, 
              (error) => { 
                this.presentToast("Não foi possível criar a tabela: preferencias" + error);
              });
          },
          (error) => {
            this.presentToast("Erro ao abrir banco de dados " + error);
          });

      }

      this.platform.registerBackButtonAction(() => {

        let activePortal = this.ionicApp._loadingPortal.getActive() ||
        this.ionicApp._modalPortal.getActive() ||
        this.ionicApp._toastPortal.getActive() ||
        this.ionicApp._overlayPortal.getActive();

        let view = this.nav.getActive();
        let currentRootPage = view.component.name;


        if (activePortal) {
          activePortal.dismiss();
        }
        else if (this.menuCtrl.isOpen()) {
          this.menuCtrl.close();
        }
        else if (this.nav.canGoBack() || view && view.isOverlay) {
          this.nav.pop();
        }
        else if (currentRootPage == "HomePage") {
          this.appMinimize.minimize().then(
            success => console.log('Closed'),
            err => console.log('Something went wrong')
          );
        } else if (currentRootPage == "OrcamentoPage") {
          let alert = this.alertCtrl.create({
            title: 'Deseja fazer logoff ?',
            message: '',
            buttons: [
            {
              text: 'Cancelar',
              role: 'cancel',
              handler: () => {
                alert.dismiss();
              }
            },
            {
              text: 'ok',
              handler: () => {
                this.nav.setRoot(HomePage);
              }
            }
            ]
          });
          alert.present();
        }else if (currentRootPage == "PreferenciasPage") {
          this.nav.setRoot(OrcamentoPage);
        } else if (currentRootPage == "CarrinhoPage") {
          this.nav.setRoot(OrcamentoPage);
        } else if (currentRootPage == "FinalizaPage") {
          this.nav.setRoot(OrcamentoPage);
        } else if (currentRootPage == "ConfigPage") {
          this.nav.setRoot(HomePage);
        }
      });
      
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
}

public presentToast(mensagem) {
  let toast = this.toastCtrl.create({
    message: mensagem,
    duration: 3000
  });
  toast.present();
}

public openPage(page) {
  this.nav.setRoot(page.component);
}
}

#2

“code not work” is not a good error description. How do you think we should help you now?


#3

This code was running normally, but when compiling with --prod, it does not work in the app.


#4

$5 on “failure to ensure platform was ready before trying to interact with it”.


#5

You’ve got a deal at $2.50


#6

What ? I did not understand


#7

You should make sure the platform is ready before you are executing code that requires the platform to be ready.


#8

So, this code is inside this.platform.ready (). Then (() => {


#9

This code will certainly not work in production. You can’t rely on the page name to stay the same, as it will undergo minification when built with --prod and thus have a different page name when in production mode.

You will have to find all alternate route for figuring out the current page name, or restructure so that you don’t need to know what the current page is outside of it’s respective class.


#10

I did not understand you, sorry…

This code will certainly not work in production. You can’t rely on the page name to stay the same, as it will undergo minification when built with --prod and thus have a different page name when in production mode.
“You will have to find all alternate route for figuring out the current page name, or restructure so that you don’t need to know what the current page is outside of it’s respective class.”


#11

So in your back button handler, you have a lot of checks for things like:

if (currentRootPage == "HomePage") {

This won’t work in production. It will wind up making the home page name something like “P1” in order to save on space.


#12

Understand, thanks. But how to solve it now ? I can use one variable in after enter in page ?


#13

What would I use something in common with every page to do this check?


#14

Solution:
let currentRootPage = view.component;
if (currentRootPage == HomePage) { <-- without " "(“HomePage”);

Solution by my boss!

this.platform.registerBackButtonAction(() => {

    let activePortal = this.ionicApp._loadingPortal.getActive() ||
    this.ionicApp._modalPortal.getActive() ||
    this.ionicApp._toastPortal.getActive() ||
    this.ionicApp._overlayPortal.getActive();

    let view = this.nav.getActive();
    let currentRootPage = view.component;


    if (activePortal) {
      activePortal.dismiss();
    }
    else if (this.menuCtrl.isOpen()) {
      this.menuCtrl.close();
    }
    else if (this.nav.canGoBack() || view && view.isOverlay) {
      this.nav.pop();
    }
    else if (currentRootPage == HomePage) {
      this.appMinimize.minimize().then(
        success => console.log('Fechado'),
        err => console.log('Algo errado:')
      );
    } else if (currentRootPage == OrcamentoPage) {
      let alert = this.alertCtrl.create({
        title: 'Deseja fazer logoff ?',
        message: '',
        buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          handler: () => {
            alert.dismiss();
          }
        },
        {
          text: 'ok',
          handler: () => {
            this.nav.setRoot(HomePage);
          }
        }
        ]
      });
      alert.present();
    }else if (currentRootPage == PreferenciasPage) {
      this.nav.setRoot(OrcamentoPage);
    } else if (currentRootPage == CarrinhoPage) {
      this.nav.setRoot(OrcamentoPage);
    } else if (currentRootPage == FinalizaPage) {
      this.nav.setRoot(OrcamentoPage);
    } else if (currentRootPage == ConfigPage) {
      this.nav.setRoot(HomePage);
    }
  });

#15

I really dislike huge monolithic functions like this. Instead, I would have separate back button handlers within each page, that are enabled and disabled via lifecycle events.


#16

I’m newbie! ;S I need use it!


#17

Perfect Solution !!!