ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

RC-0: navigation failed to blank page

Open ecureuill opened this issue 10 years ago • 25 comments

Short description of the problem:

navCtrl.push(...) after a login attempt works only with Chrome developer tools (android device). Otherwise, it goes to the redirect page, and quickly shows a blank page instead.

It's the same behavior with setRoot

UPDATE In a more simple scenery, with no redirect before login, still leads to blank page. https://github.com/ecureuill/Ionic2RC-Auth0.git3

So I guess it is not a bug specific to method push() or setRoot. Could be a problem between ionic navigation and angular navigation? UPDATE

What behavior are you expecting?

Steps to reproduce:

  1. ionic serve
  2. open Chrome developers tool (android device)
  3. navigate (works)
  4. ionic serve
  5. navigate (don't work)
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AuthService } from '../../providers/auth0'

import { HomePage } from '../home/home';


@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class LoginPage {

    constructor(public navCtrl: NavController, private auth: AuthService) {
        this.redirectTo();
    }

    public get autenticado(): boolean {
        return this.auth.authenticated();
    }

    login() {
        this.auth.lock.show();
    }

    redirectTo() {
        if (this.auth.authenticated()) {
            this.navCtrl.push(HomePage);
        } else {
            this.auth.lock.on('authenticated', authResult => {
                this.navCtrl.push(HomePage);
            });
        }
    }
}

Other information: (e.g. stacktraces, related issues, suggestions how to fix, stackoverflow links, forum links, etc) https://forum.ionicframework.com/t/page-coming-as-blank-after-login-in-ionic-2-rc0/65077

Which Ionic Version? 1.x or 2.x 2.0RC-0

Run ionic info from terminal/cmd prompt: (paste output below)

Your system information:

Cordova CLI: 6.3.1 Gulp version: CLI version 3.9.1 Gulp local:
Ionic Framework Version: 2.0.0-rc.0 Ionic CLI Version: 2.1.0 Ionic App Lib Version: 2.1.0-beta.1 OS: Distributor ID: Debian Description: Debian GNU/Linux 8.6 (jessie) Node Version: v4.5.0

ecureuill avatar Sep 30 '16 23:09 ecureuill

Try calling redirectTo() after the LoginPage has entered, with ionViewDidEnter.

manucorporat avatar Sep 30 '16 23:09 manucorporat

Same behaviour. Bellow, more code details

app.module.ts

import { NgModule } from '@angular/core';
import { Storage } from '@ionic/storage';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';

/* --------------- PAGES ------------------ */
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
/* --------------- PROVIDERS ------------------ */
import { AuthService } from '../providers/auth0';
///JWT Config
import { AuthHttp, AuthConfig} from 'angular2-jwt';
import { Http } from '@angular/http';

 export function getAuthHttp(http) {
     return new AuthHttp(new AuthConfig({
       noJwtError: true
     }), http);
 }


@NgModule({
  declarations: [
    MyApp,
    LoginPage,
    HomePage
   ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    LoginPage,
      ],
  providers: [
    Storage,
    AuthHttp,
    AuthService,
    {
      provide: AuthHttp,
      useFactory: getAuthHttp,
      deps:[Http]
    }
  ]
})
export class AppModule { }

login.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../providers/auth0'
import { HomePage } from '../home/home';


@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class LoginPage {

    constructor(public navCtrl: NavController, public auth: AuthService) {
    }

    public get autenticado(): boolean {
        return this.auth.authenticated();
    }

    login() {
        this.auth.lock.show();
    }

    ionViewDidEnter() {
        this.redirectTo();

    }

    redirectTo() {
        if (this.auth.authenticated()) {
            this.navCtrl.setRoot(HomePage);
                        this.navCtrl.push(HomePage)
        } else {
            this.auth.lock.on('authenticated', authResult => {
                this.navCtrl.setRoot(HomePage);
            });
        }
    }
}

login.html

<ion-header>
    <ion-navbar>
        <ion-title>login</ion-title>
    </ion-navbar>
</ion-header>
<ion-content padding *ngIf="auth.authenticated()">
    <button ion-button (click)="redirectTo()" >Home</button>
    {{auth.authenticated()}}
</ion-content>
<ion-content padding *ngIf="!auth.authenticated()">
    <button ion-button (click)="login()">Login</button>
    {{auth.authenticated()}}
</ion-content>

auth0.ts

import {Storage} from '@ionic/storage';
import {AuthHttp, JwtHelper, tokenNotExpired} from 'angular2-jwt';
import {Injectable, NgZone} from '@angular/core';
import {Observable} from 'rxjs/Rx';

// Avoid name not found warnings
declare var Auth0: any;
declare var Auth0Lock: any;
// declare var faker = require('faker');

export class Auth0Vars {
  //application's clientId in Auth0.
    static AUTH0_CLIENT_ID = "...";
    static AUTH0_DOMAIN = "...";
}

@Injectable()
export class AuthService {

  jwtHelper: JwtHelper = new JwtHelper();

  auth0 = new Auth0({ clientID: Auth0Vars.AUTH0_CLIENT_ID, domain: Auth0Vars.AUTH0_DOMAIN });

  lock = new Auth0Lock(Auth0Vars.AUTH0_CLIENT_ID, Auth0Vars.AUTH0_DOMAIN
    , {
    redirect: false, //popup options
    autoclose: true,
    avatar: null,
    closable: false,
    rememberLastLogin: false,
    language: 'pt-br',
    theme: {
      primaryColor: 'green',
      logo: 'assets/img/logo.jpg',
      labeledSubmitButton: true //This option indicates whether or not the submit button
      // should have a label, and defaults to true. When set to false, an icon will be shown instead.
    },
    languageDictionary: {
      title: "Teeth"
    },
    }
  );

  local: Storage;
  refreshSubscription: any;
  user: Object;
  zoneImpl: NgZone;

  constructor(private authHttp: AuthHttp, zone: NgZone, local : Storage) {
    this.zoneImpl = zone;
    this.local = local;

    this.lock.show();

    // Check if there is a profile saved in local storage
    this.local.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });


    this.lock.on('authenticated', authResult => {
      this.local.set('id_token', authResult.idToken);

      // Fetch profile information
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // TODO: tratar erro 
          console.error("erro ao retornar perfil", error);
          return;
        }

        profile.user_metadata = profile.user_metadata || {};
        this.local.set('profile', JSON.stringify(profile));
        this.user = profile;
      });

      this.lock.hide();

      this.local.set('refresh_token', authResult.refreshToken);
      this.zoneImpl.run(() => this.user = authResult.profile);
      // Schedule a token refresh
      this.scheduleRefresh();

    });

  }

  public authenticated() {
    // Check if there's an unexpired JWT
    return tokenNotExpired();
  }

  public login() {
    // Show the Auth0 Lock widget
    this.lock.show();
  }

  public logout() {
    this.local.remove('profile');
    this.local.remove('id_token');
    this.local.remove('refresh_token');
    this.zoneImpl.run(() => this.user = null);
    // Unschedule the token refresh
    this.unscheduleRefresh();
  }

  public scheduleRefresh() {
    // If the user is authenticated, use the token stream
    // provided by angular2-jwt and flatMap the token
    let source = this.authHttp.tokenStream.flatMap(
      token => {
        // The delay to generate in this case is the difference
        // between the expiry time and the issued at time
        let jwtIat = this.jwtHelper.decodeToken(token).iat;
        let jwtExp = this.jwtHelper.decodeToken(token).exp;
        let iat = new Date(0);
        let exp = new Date(0);

        let delay = (exp.setUTCSeconds(jwtExp) - iat.setUTCSeconds(jwtIat));

        return Observable.interval(delay);
      });

    this.refreshSubscription = source.subscribe(() => {
      this.getNewJwt();
    });
  }

  public startupTokenRefresh() {
    // If the user is authenticated, use the token stream
    // provided by angular2-jwt and flatMap the token
    if (this.authenticated()) {
      let source = this.authHttp.tokenStream.flatMap(
        token => {
          // Get the expiry time to generate
          // a delay in milliseconds
          let now: number = new Date().valueOf();
          let jwtExp: number = this.jwtHelper.decodeToken(token).exp;
          let exp: Date = new Date(0);
          exp.setUTCSeconds(jwtExp);
          let delay: number = exp.valueOf() - now;

          // Use the delay in a timer to
          // run the refresh at the proper time
          return Observable.timer(delay);
        });

      // Once the delay time from above is
      // reached, get a new JWT and schedule
      // additional refreshes
      source.subscribe(() => {
        this.getNewJwt();
        this.scheduleRefresh();
      });
    }
  }

  public unscheduleRefresh() {
    // Unsubscribe fromt the refresh
    if (this.refreshSubscription) {
      this.refreshSubscription.unsubscribe();
    }
  }

  public getNewJwt() {
    // Get a new JWT from Auth0 using the refresh token saved
    // in local storage
    this.local.get('refresh_token').then(token => {
      this.auth0.refreshToken(token, (err, delegationRequest) => {
        if (err) {
          alert(err);
        }
        this.local.set('id_token', delegationRequest.id_token);
      });
    }).catch(error => {
      console.log(error);
    });

  }
}

ecureuill avatar Oct 01 '16 00:10 ecureuill

having the same issue!

update:

Just built the app for android. Same issue there.

fishgrind avatar Oct 01 '16 01:10 fishgrind

another update:

if chrome dev tools device is set to an IOS device there is no problem. If it is set to an Android device the problem is also there in dev tools

fishgrind avatar Oct 02 '16 03:10 fishgrind

I have the same problem. After a successful login I set the rootPage using:

this.navCtrl.setRoot(HomePage);

and this was giving me a white page of doom but was able to fix the issue by replacing:

<ion-nav id="nav" #content [root]="rootPage"></ion-nav>

with

<ion-nav id="nav" #content></ion-nav>

on my home page.

leommoore avatar Oct 02 '16 20:10 leommoore

@leommoore i tried your solution,

unfortunately it doesnt work for me. Ik does however now show the navbar but thats it..

fishgrind avatar Oct 02 '16 20:10 fishgrind

Please, have a look in this https://github.com/ecureuill/Ionic2RC-Auth0.git3

After login, with no redirect, still lead to blank page. So, problem is not specific to .push

ecureuill avatar Oct 03 '16 20:10 ecureuill

To try to figure out whats is the problem, Auth0 team ask me about the navigation. Can someone help to answer this?

ecureuill avatar Oct 03 '16 20:10 ecureuill

Hello all! Since this seems to be an Auth0 related issue and not a framework issue I am going to close this issue for now. Thanks!

jgw96 avatar Oct 04 '16 15:10 jgw96

@jgw96 not really, my login page just posts to my own json api without using Auth0, I don't use any plugin for this, my login process sends and receives everything through http post.

after a succesfull login i go to the login page using: this.navCtrl.setRoot(ProfilePage);

This worked in beta11 and 10.

Also other pages where i set the root the same way work fine, those are all fired by a click though, that is the only difference.

The problem is only on android devices, google chrome, and in the chrome developer tools if you set the device to an android device, ios devices in developer tools work fine.

Workaround there is a workaround though. Wrapping the setRoot in a timeout fixes the problem.

let _self = this
 setTimeout(function(){
        _self.navCtrl.setRoot(ProfilePage);
        console.log('timeout finished')
        }, 300);

So this is not an Auth0 issue but a framework related issue.

fishgrind avatar Oct 04 '16 15:10 fishgrind

If it'st necessary a timeout to works, maybe it's related to 8449

I try call my redirect method in ngAfterViewInit instead ionViewDidEnter and it's seems to work. Moreover, fix my problem of keep logged after login

@fishgrind can you try this?

ecureuill avatar Oct 04 '16 17:10 ecureuill

I'm kinda having same issue. I'm checking user auth(from firebase) with ngOnInit() and define rootPage on app.component.ts. When I run the app on my device, its just blank page without any console errors. Then if I switch different app and return my app, it works.

candelibas avatar Oct 04 '16 17:10 candelibas

@ecureuill

unfortunately that isnt the issue as i am calling setRoot from a function after receiving data from the json api. But thanks for your input!

fishgrind avatar Oct 04 '16 17:10 fishgrind

If I use image on page, it works :)

reijosirila avatar Oct 05 '16 18:10 reijosirila

After moving to RC0 I did not have this problem. But after I got info that one page is blank after opening, next I run it in with ionic serve and wow... even at startup it is blank. But I noticed a small flicker when I see login page, and after that nothing there. DOM elements seems to be just fine.

Used remove [root]="rootPage" from above and did work somehow, not sure if it solution or temporal effect. I do not use any side frameworks...

ghost avatar Oct 05 '16 19:10 ghost

it's really funny. DOM elements/page are there, i can inspect those. But they're not visible. All CSS opacity and everything seems OK, but just elements are not visible...

reijosirila avatar Oct 05 '16 19:10 reijosirila

Yes, I've noticed that. After redirect to HomePage, it come back to LoginPage, and I guess that it is "blank" because content should be resized.

ecureuill avatar Oct 05 '16 20:10 ecureuill

Havent figured out how to reproduce it but... in my case.. screenshot 2016-10-06 01 57 59

reijosirila avatar Oct 06 '16 07:10 reijosirila

Link to the same task which has assignee: https://github.com/driftyco/ionic/issues/8510

ghost avatar Oct 06 '16 07:10 ghost

Update: I guess the problem is with some transition, because I have this problem only with nav.push, nav.pop but not with nav.setRoot, which works perfectly pages. Also it is strange that some pages have this issue all the time while others do not have (depends on items on the page?)

As a workaround I navigate with setRoot for problematic pages and overwritten backbutton actions:

      platform.ready().then(() => {
            platform.registerBackButtonAction(() => {

with inside code of such type:

if (this.nav.canGoBack() || this.nav.getActive() && this.nav.getActive().isOverlay
                ) {
                    Logger.log("Popping back");
                    this.nav.pop();
                }
                else if (this.nav.getActive() && this.nav.getActive().instance && this.nav.getActive().instance.isRootPage
                ) {

The instance is the Page class that you have at the moment and you can put there any property you want, so isRootPage is true/false for my home page. Thus you can intercept navigation and place pages from one place whatever you want, based on class properties.

ghost avatar Oct 06 '16 11:10 ghost