I'm looking to set up firebase authentication on a NativeScript app and I'm having a hard time figuring out the best practice to set up the routes/components.
What I like to do is set it up like any typical modern app where if the user is not logged in then they are redirected to the login page. If there are logged in then they skip the login page and are redirected to their dashboard.
I have a user.service like this
import { Injectable } from '@angular/core';
import { RouterExtensions } from 'nativescript-angular/router';
import firebase = require("nativescript-plugin-firebase");
@Injectable()
export class UserService {
private uid;
private route;
constructor(router: RouterExtensions){
this.route = router;
}
public initFirebase(){ //This gets called from AppComponent Constructor
let that = this;
firebase.init({
onAuthStateChanged: function(data) {
if (data.loggedIn) {
that.route.navigate(["/dash"]);
} else {
console.log("NOT logged in.. redirecting to login");
that.route.navigate(["/login"]);
}
}
}).then(
(instance) => {
console.log("Firebase Initialized");
},
(error) => {
console.log("firebase.init error: " + error);
}
);
}
And in the router what I currently have set up is
export const routes = [
{ path: "", component: LoginComponent },
{ path: "dash", component: DashComponent},
{ path: "login", component: LoginComponent}
];
But that flashes the login page before it redirects to the dash which is terrible.
I also tried to do this..
export const routes = [
{ path: "", component: AppComponent },
{ path: "dash", component: DashComponent},
{ path: "login", component: LoginComponent},
];
But this for reason makes Firebase initialize twice.
SO finally I tried this..
export const routes = [
{ path: "", component: DashComponent},
{ path: "dash", component: DashComponent},
{ path: "login", component: LoginComponent},
];
But this runs the DashComponent constructor before I want it to. I want firebase init in user.service run FIRST and then DashComponent run after the user service firebase init completes and redirects to dash.
What is the best practice to solve this?