没有Firebase应用程序';[默认]';已创建-调用Firebase App.initializeApp()

没有Firebase应用程序';[默认]';已创建-调用Firebase App.initializeApp(),firebase,ionic4,auth-guard,Firebase,Ionic4,Auth Guard,在我的项目中实现authGuard之前,一切都很好。但是,这似乎是一个错误 我从页面中删除了authguard,它正在工作。但后来又加了回去,给了错误 App.routing.module.ts { path: 'login', loadChildren: './Users/login/login.module#LoginPageModule' }, { path: 'students/:uName', loadChildren: './Academic/Students/student

在我的项目中实现authGuard之前,一切都很好。但是,这似乎是一个错误

我从页面中删除了authguard,它正在工作。但后来又加了回去,给了错误

App.routing.module.ts

  { path: 'login', loadChildren: './Users/login/login.module#LoginPageModule' },
  { path: 'students/:uName', loadChildren: './Academic/Students/students/students.module#StudentsPageModule',canActivate: [AuthGuard],},
  { path: 'registerclass', loadChildren: './Academic/Students/registerclass/registerclass.module#RegisterclassPageModule',canActivate: [AuthGuard], },
  { path: 'schedule', loadChildren: './Academic/Students/schedule/schedule.module#SchedulePageModule',canActivate: [AuthGuard], },
  { path: 'faculties', loadChildren: './Academic/Faculty/faculties/faculties.module#FacultiesPageModule',canActivate: [AuthGuard], },
  { path: 'addclass', loadChildren: './Academic/Faculty/addclass/addclass.module#AddclassPageModule',canActivate: [AuthGuard], },

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { AngularFireModule } from '@angular/fire'; //To initialize firebaseconfig
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule } from '@angular/fire/firestore';

var firebaseConfig = {
  apiKey: "AIzaSyC7f8sjVR-cSeeee3ZbEErwOQReowwpTL0",
  authDomain: "msuproject-74e5a.firebaseapp.com",
  databaseURL: "https://msuproject-74e5a.firebaseio.com",
  projectId: "msuproject-74e5a",
  storageBucket: "msuproject-74e5a.appspot.com",
  messagingSenderId: "748587348290",
  appId: "1:748587348290:web:e10fe4336779cd2ee158db",
  measurementId: "G-GE58MG9QF6"
};
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(firebaseConfig),
    AngularFireAuthModule,
    AngularFirestoreModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
import { environment } from '../environments/environment';

...
    imports: [
...
AngularFireModule.initializeApp(environment.firebaseConfig),
...
auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate,ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,Router } from '@angular/router';
import { Observable } from 'rxjs';
import * as firebase from 'firebase/app'
import 'firebase/auth'


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {


  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }


}// close of class Authguard
 constructor(private router: Router,
                private afAuth: AngularFireAuth,
                private ngZone: NgZone) { }

 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.afAuth.auth.onAuthStateChanged((user: firebase.User) => this.ngZone.run(() => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }
home.html

<ion-card style="text-align: center; background-color: rgb(19, 4, 4);">
        <nav class="navCard">
            <h1 class="h1Card">
                <a [routerLink]="['/login']">Login</a> |
                <a [routerLink]="['/faculties']">Faculty</a> |
                <a href="https://lib.murraystate.edu/">Library</a> |
                <a href="#">Info</a> 
            </h1>
          </nav>
        </ion-card>

|

因此,当我单击“Faculty”时,它应该将我带到Faculty页面,而不是使页面崩溃。

首先将
firebaseconfig
对象移动到另一个
ts
文件中,然后在
auth.guard.ts
中执行以下操作:

import * as config from './config.ts';

let firebaseInit = firebase.initializeApp(config.firebaseConfig);

另一个解决方案使用firebase javascript SDK,但由于您正在导入AngularFire,因此也可以使用它

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate,ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,Router } from '@angular/router';
import { Observable } from 'rxjs';
import * as firebase from 'firebase/app'
import 'firebase/auth'


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {


  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }


}// close of class Authguard
 constructor(private router: Router,
                private afAuth: AngularFireAuth,
                private ngZone: NgZone) { }

 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.afAuth.auth.onAuthStateChanged((user: firebase.User) => this.ngZone.run(() => {
        if (user) {
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigate(['/login']);
          resolve(false);
        }
      });
    });
  }

为什么不使用@angular/fire提供给你的方法呢?你能再解释一下吗?你已经安装了这个软件包,但是你在你的守卫中使用了“普通”的firebase方法。我不知道为什么它一眼就崩溃了,但我看不出有什么理由不使用你可以使用的服务。很抱歉,反应太晚了,但你怎么知道它是香草的还是其他的?我正在使用,但没有足够的知识。如果您提供一些参考,而不是导入为您带来繁重负担的
@angular/fire/auth
,那就太好了。不确定它是什么时候被添加到包中的,但是文档中有一个部分使用了.Moved并插入了导入配置。那我该怎么处理firebaseInit?使用它。。。Do
firebaseInit.auth()…等
你试过了吗?这对我很有用。我没有看到任何错误。非常感谢你。