Google authentication in firebase showing blank screen Progressive Web App

后端 未结 3 760
轮回少年
轮回少年 2021-02-07 05:27

I am on the way to create my first Progressive web app which uses firebase for storing data. I am also using Gmail as an entry point for all the users that would us

3条回答
  •  我寻月下人不归
    2021-02-07 05:57

    I had almost same behavior on my pet web app. For my self I solve it by the next steps:

    1. I move firebase initialization to the app.module.ts

    @NgModule({
        ...
        providers: [
            { provide: APP_INITIALIZER, useFactory: appConfig, deps: [AuthService], multi: true }
        ]
    })
    
    export function appConfig(authService) {
        const app = firebase.initializeApp({
            apiKey
            authDomain
        });
        return () => new Promise((resolve, reject) => {
            firebase.auth()
            .onAuthStateChanged(data => {
                if (data) {
                  firebase.auth().currentUser.getToken()
                    .then((token: string) => authService.setToken(token););
                }
                resolve(true);
            }, error => resolve(true));
        });
    }

    1. Redirection to LoginPage I managed in auth.guard.ts

    export class AuthGuard implements CanActivate {
        constructor(
            private authService: AuthService,
            private router: Router
        ) {}
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
            if (this.authService.isAuthenticated()) {
                return true;
            } else {
                this.router.navigate(['/signin']);
                return false;
            }
        }
    }

    1. I had the next code in my auth.service.ts

    export class AuthService {
        token: string;
    
        signinUser(email: string, password: string) {
            return new Promise((resolve, reject) => {
                firebase.auth().signInWithEmailAndPassword(email, password)
                    .then(resp => {
                        firebase.auth().currentUser.getToken()
                            .then((token: string) => {
                                this.token = token;
                                resolve(resp);
                            }).catch(reject);
                        return resp;
                    })
                    .catch(reject);
                });
        }
    
        signoutUser() {
            return firebase.auth().signOut()
                .then(resp => this.token = null);
        }
    
        getToken() {
            firebase.auth().currentUser.getToken()
                .then((token: string) => this.setToken(token));
            return this.token;
        }
        
        setToken(token) {
          this.token = token;
        }
    
        isAuthenticated() {
            return this.token != null;
        }
    }

    I hope it will be helpful for you.

提交回复
热议问题