Firebase authentication change listener is never triggered in nativescript-angular app

70 views Asked by At

I using nativescript firebase (@nativescript/firebase) plugin version 11.1.3 in my project. I want to check if the user is logged in at the start of the application and redirect to 'items page' or login accordingly. Therefore, I've included onAuthStateChanged option inside firebase.init which is called inside ngInit of AppComponent:

import {Component, OnInit} from "@angular/core";
import {firebase} from "@nativescript/firebase";
import {BackendService} from "./shared/services/backend.service";

@Component({
    selector: "ns-app",
    templateUrl: "./app.component.html"
})
export class AppComponent implements OnInit {

    ngOnInit() {

        firebase.init({
            // -- persist: true,

            onAuthStateChanged: (data: any) => {
                console.log(JSON.stringify(data))
                if (data.loggedIn) {
                    BackendService.token = data.user.uid;

                } else {
                    BackendService.token = "";
                }
            }
        }).then(
            () => {
                console.log("firebase.init done");
            },
            error => {
                console.log(`firebase.init error: ${error}`);
            }
        );
    }
}

BackendService is responsible for saving token to application settings. onLogin() method below resides in login component which authenticate and redirect user to items views:

onLogin(): void {

        this.isAuthenticating = true;

        this.firebaseService.login(this.user)
            .then(result => {
                this.isAuthenticating = false;
                this.routerEx.navigate(["/items"], {clearHistory: true});
                console.log(JSON.stringify(result));
            })
            .catch(error => {
                this.isAuthenticating = false;
                alert((error.split(':')[1]))
            });
    }

I have an authentication gaurd on items component which redirect users back to login component if 'token' (UID currently) is not set.

    canActivate() {
        if (BackendService.isLoggedIn()) {
            return true;
        } else {
            this.routerEx.navigate(["/login"]);
            return false;
        }
    }

From the console logs, it clearly shows that am able to login successfully but the app remains on login screen. In fact it redirect to items and auth guard redirect it back to login screen since onAuthStateChanged was not trigged and token was not set.

I've tried firebase.addAuthStateListener(listener) with onAuthStateChanged outside firebase.init and still doing the same thing. Please bear with me folks if you think my question is too obvious as I am a newbie to nativescript and still learning most of the concept.

Thanks in anticipation

0

There are 0 answers