firebase.auth()。onAuthStateChanged没有AngularFire的提供者

时间:2017-05-02 07:04:16

标签: firebase ionic2 firebase-authentication angularfire

我收到错误

未捕获(承诺):错误:没有AngularFire的提供者!

当我试图致电firebase.auth().onAuthStateChanged时。 不知道为什么会这样。请帮忙。

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';
import { Login } from '../pages/login/login';

import firebase from 'firebase';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = Login;
  isAuthenticated = false;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    firebase.initializeApp({
      apiKey: "AIzaSyC94rD8wXG0aRLTcG29qVGw8CFfvCK7XVQ",
      authDomain: "myfirstfirebaseproject-6da6c.firebaseapp.com",
    }); 

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.isAuthenticated = true;
        this.rootPage = HomePage;
      } else {
        this.isAuthenticated = false;
        this.rootPage = Login;
      }
    });

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

1 个答案:

答案 0 :(得分:0)

您的配置未正确设置。您应该在app.module.ts中使用此代码,而不是在组件中。

import {
    AngularFireModule,
    AuthMethods,
    AuthProviders
} from 'angularfire2';

...

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [
        AngularFireModule.initializeApp({
            apiKey: '<some-key>',
            authDomain: '<some-project-authdomain>',
            databaseURL: '<some-database-URL>',
            storageBucket: '<some-storage-bucket>'
        }, {
            method: AuthMethods.Password,
            provider: AuthProviders.Password
        }),
        BrowserModule,
        ...
    ]
})
class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule);

这是您应该拥有上述代码的地方。如果您没有设置提供商,则会不断收到错误。