AngularFire:从App Component访问时未初始化Firebase应用程序

时间:2018-04-02 17:01:16

标签: angular firebase firebase-authentication angularfire2

使用AngularFire正在使用Angular和Firebase,也就是说,我已经从app.component.ts以外的组件访问所有角度身份验证。

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)." name:"[DEFAULT]

我只能假设Firebase比应用程序组件晚了?有没有解决的办法?以下是有关部分。

应用组件:

import { Component } from '@angular/core';
import * as firebase from 'firebase/app';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  router;
  constructor(router: Router) {
    this.router = router;

    //Fails here.
    firebase.auth().onAuthStateChanged(user => {
      if (!user) {
        return;
      }
    });
  }
}

适用于普通组件。

...
import * as firebase from 'firebase/app';

@Component({
  selector: '....component',
  templateUrl: './....component.html',
  styleUrls: ['./....component.scss']
})
export class CustomComponent {
  constructor(private router: Router) {
    this.user = {};
    firebase.auth().onAuthStateChanged(function (user) {
      if (!user) {
        router.navigate(['../login']);
        return;
      }
    });
  }
}

应用模块

@NgModule({
  imports: [
    CommonModule,
    BrowserModule.withServerTransition({ appId: 'serverside' }),
    RouterModule.forRoot(appRoutes),
    NgbModule.forRoot(),
    AngularFireModule.initializeApp(environment.firebase),
    AppRoutingModule,
    FormsModule,
    HttpModule,
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    BrowserAnimationsModule,
    MdDialogModule,
    MdButtonModule,
    ....

1 个答案:

答案 0 :(得分:0)

您是否尝试在导入RouterModule之前导入AngularFireModule?

建议:在重定向到登录组件的路由中使用Guard