AngularFire2 TypeError:app.auth不是函数

时间:2018-01-24 21:17:50

标签: angular firebase

我正在尝试通过AngularFire2将firebase与Nebular集成。

我正在我的应用程序模块中初始化AngularFire2,当我检查它似乎是firebase应用程序正在配置,但由于某种原因auth模块没有附加或类似的东西,因为firebase.auth()为null,应该是一个功能。

调试输出

似乎firebase正在初始化。

https://user-images.githubusercontent.com/60548/35354017-c198eee2-00fd-11e8-8030-95654ebb2d5f.png screenshot 2018-01-24 11 51 16

但是它会引发TypeError。 https://user-images.githubusercontent.com/60548/35353848-50c7e506-00fd-11e8-9563-b29efef69e2c.png screenshot 2018-01-24 11 51 27

core.module.ts

const NB_CORE_PROVIDERS = [
  ...DataModule.forRoot().providers,
  ...NbAuthModule.forRoot({
    providers: {
      email: {
        service: NbFirebaseAuthProvider,
        config: {
        },
      },
    },
  }).providers,
  AnalyticsService,
  NbFirebaseAuthProvider,
];

@NgModule({
  imports: [
    CommonModule,
  ],
  exports: [
    NbAuthModule,
  ],
  declarations: [],
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }

  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders>{
      ngModule: CoreModule,
      providers: [
        ...NB_CORE_PROVIDERS,
      ],
    };
  }
}

app.module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpModule,
    AngularFireModule.initializeApp({
      apiKey: "<removed>",
      authDomain: "<removed>",
      databaseURL: "<removed>",
      projectId: "<removed>",
      storageBucket: "<removed>",
      messagingSenderId: "65580220719"
    }),
    AngularFireAuthModule,
    AppRoutingModule,
    NgbModule.forRoot(),
    ThemeModule.forRoot(),
    CoreModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    { provide: APP_BASE_HREF, useValue: '/' },
  ],
})
export class AppModule {
}

火力-auth.provider.ts

@Injectable()
export class NbFirebaseAuthProvider extends NbAbstractAuthProvider {
  constructor(
    private afa : AngularFireAuth
  ) {
    super();
    console.log(this.afa);
  }

  protected defaultConfig: NgEmailPassAuthProviderConfig = {
    login: {
      redirect: {
        success: '/',
        failure: null,
      },
    },
    register: {
      redirect: {
        success: '/',
        failure: null,
      },
    },
    requestPass: {
      redirect: {
        success: '/auth/login',
        failure: null,
      },
    },
    resetPass: {
      redirect: {
        success: '/auth/login',
        failure: '/auth/reset-password',
      },
    },
    logout: {
      redirect: {
        success: '/auth/login',
        failure: null,
      },
    },
  };


  /**
   * Firebase authentication.
   *
   * @param data any
   * @returns Observable<NbAuthResult>
   */
  authenticate(data?: any): Observable<NbAuthResult> {
    console.log(this.afa);
    return Observable.fromPromise(this.afa.auth.signInWithEmailAndPassword(data.email, data.password))
      .map((res) => {
        return this.processSuccess(res, this.getConfigValue('login.redirect.success'), [res.message]);
      })
      .catch((res) => {
        return Observable.of(
          this.processFailure(res, this.getConfigValue('login.redirect.failure'), [res.message]),
        );
      });
  }

  /**
   * Firebase registration.
   *
   * @param data any
   * @returns Observable<NbAuthResult>
   */
  register(data?: any): Observable<any> {
    return Observable.fromPromise(this.afa.auth.createUserWithEmailAndPassword(data.email, data.password))
      .map((res) => {
        return Observable.fromPromise(this.afa.auth.currentUser.updateProfile({
          displayName: data.fullName,
          photoURL: '',
        })).map((update) => {
          return this.processSuccess(res, this.getConfigValue('register.redirect.success'), [res.message]);
        });
      })
      .catch((res) => {
        return Observable.of(
          this.processFailure(res, this.getConfigValue('register.redirect.failure'), [res.message]),
        );
      });
  }

  /**
   * Firebase restore password.
   *
   * @param data any
   * @returns Observable<NbAuthResult>
   */
  requestPassword(data?: any): Observable<NbAuthResult> {
    return Observable.fromPromise(this.afa.auth.sendPasswordResetEmail(data.email))
      .map((res) => {
        return this.processSuccess(res, this.getConfigValue('requestPass.redirect.success'), []);
      })
      .catch((res) => {
        return Observable.of(this.processFailure(res,  this.getConfigValue('requestPass.redirect.failure'),
          [res.message]));
      });
  }

  /**
   * Firebase reset password.
   *
   * @param data any
   * @returns Observable<NbAuthResult>
   */
  resetPassword(data?: any): Observable<NbAuthResult> {
    if (this.afa.auth.currentUser) {
      return Observable.fromPromise(this.afa.auth.currentUser.updatePassword(data.password))
        .map((res) => {
          return this.processSuccess(res, this.getConfigValue('resetPass.redirect.success'), []);
        })
        .catch((res) => {
          return Observable.of(this.processFailure(res,  this.getConfigValue('resetPass.redirect.failure'),
            [res.message]));
        });
    }

    return Observable.of(this.processFailure([],  this.getConfigValue('resetPass.redirect.failure'),
      ['Please, sign in to be able to reset your password']));
  }

  /**
   * Firebase logout.
   *
   * @param data any
   * @returns Observable<NbAuthResult>
   */
  logout(data?: any): Observable<NbAuthResult> {
    return Observable.fromPromise(this.afa.auth.signOut())
      .map((res) => {
        return this.processSuccess(res, this.getConfigValue('logout.redirect.success'),  []);
      })
      .catch((res) => {
        return Observable.of(this.processFailure(res, this.getConfigValue('logout.redirect.failure'),
          [res.message]));
      });
  }

  private processSuccess(response?: any, redirect?: any, messages?: any): NbAuthResult {
    return new NbAuthResult(true, response, redirect, [], messages);
  }

  private processFailure(response?: any, redirect?: any, errors?: any): NbAuthResult {
    return new NbAuthResult(false, response, redirect, errors, []);
  }
}

1 个答案:

答案 0 :(得分:0)

这是因为你正在解析为AngularFireAuth的app实例还没有附加auth方法。您需要import { AngularFireAuth } from 'angularfire2/auth';中的firebase-auth.provider.ts

我建议使用codesandbox来确保我们看到您正在使用的相同代码。

*编辑:如果你使用新的api,你可以这样做 import * as firebase from 'firebase/app';,然后致电firebase.auth()