AngularFire2 TypeError:app.auth不是函数 [英] AngularFire2 TypeError: app.auth is not a function

查看:86
本文介绍了AngularFire2 TypeError:app.auth不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过AngularFire2与 Nebular 集成Firebase.

I'm trying to integrate firebase via AngularFire2 with Nebular.

我正在我的应用程序模块中初始化AngularFire2,当我检查似乎配置了Firebase应用程序时,但由于某种原因未连接auth模块或类似的东西,因为firebase.auth()为null,应为一个功能.

I am initializing AngularFire2 in my app module and when I check it seems like the firebase app is getting configured, but for some reason the auth module is not attached or something like that because firebase.auth() is null and should be a function.

好像Firebase正在初始化.

It seems as if firebase is getting initialized.

https://user-images. githubusercontent.com/60548/35354017-c198eee2-00fd-11e8-8030-95654ebb2d5f.png

但是随后它抛出TypeError. https://user-images.githubusercontent.com /60548/35353848-50c7e506-00fd-11e8-9563-b29efef69e2c.png

But then it throws a TypeError. https://user-images.githubusercontent.com/60548/35353848-50c7e506-00fd-11e8-9563-b29efef69e2c.png

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 {
}

firebase-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, []);
  }
}

推荐答案

这是因为您要解析到AngularFireAuth的应用程序实例尚未附加auth方法.您需要firebase-auth.provider.ts中的import { AngularFireAuth } from 'angularfire2/auth';.

It's because the app instance you are parsing to AngularFireAuth doesn't have the auth method attached to it yet. You need import { AngularFireAuth } from 'angularfire2/auth'; in firebase-auth.provider.ts.

我建议使用codeandbox来确保我们看到的是与您使用的相同的代码.

I'd suggest using codesandbox to make sure we are seeing the same code you are working with.

*如果您正在使用新的api,则可以执行 import * as firebase from 'firebase/app';,然后调用firebase.auth()

* if you are using the new api, you can do import * as firebase from 'firebase/app'; and then call firebase.auth()

这篇关于AngularFire2 TypeError:app.auth不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆