如何在使用angularfire2时访问本机Firebase对象?

Rob*_*man 12 firebase firebase-authentication angularfire2

我正在使用AngularFire2(2.0.0-beta.2)与angular2(2.0.0-rc.4)组合.我想从Angularfire2访问本机firebase对象(不是AngularFire根对象).

在我的组件中,我想进行如下调用:

firebase.auth().currentUser.updateEmail("user@example.com")
Run Code Online (Sandbox Code Playgroud)

firebase是本机firebase对象,就像你从下面的片段得到的那样:

<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>
  <script>
    // Initialize Firebase
    // TODO: Replace with your project's customized code snippet
    var config = {
      apiKey: "apiKey",
      authDomain: "projectId.firebaseapp.com",
      databaseURL: "https://databaseName.firebaseio.com",
      storageBucket: "bucket.appspot.com",
    };
    firebase.initializeApp(config);
  </script>
Run Code Online (Sandbox Code Playgroud)

但我不明白如何设置我的angular2组件,以便firebase对象在其中可见.可能是一个非常简单的问题需要解决,但我不知道如何解决 - 我不是一个有角度的专家.我希望有和AngularFire api得到对象,但没有.

此外,我试图这样做的原因是我不认为angularfire2 api是完整的(这可以理解,因为它仍处于测试版)并且我正在努力解决这个问题.例如,我想更新用户的电子邮件地址或密码,或向他们发送忘记密码的电子邮件.AngularFire2中似乎还没有这个功能,所以我尝试使用本机Firebase对象来实现.

Kho*_*Phi 8

如果您在2016年9月开始阅读此内容,这种方法对您来说可能听起来不错.

请参阅代码以获得更好的理解:

import { Component, Inject } from '@angular/core';
import { AngularFire, FirebaseApp } from 'angularfire2';

@Component({
  templateUrl: 'app/auth/resetpassword.component.html'
})

export class ResetpassComponent {
  public auth: any;
  constructor(private af: AngularFire, @Inject(FirebaseApp) firebaseApp: any) {
    this.auth = firebaseApp.auth()
    console.log(this.auth);
  }

  // formData.value.email = 'your@email.com';
  onSubmit(formData) {
     if(formData.valid) {
       console.log('Sending email verification');
       this.auth.sendPasswordResetEmail(formData.value.email)
         .then( (response) => {
           console.log('Sent successfully');
         })
         .catch( (error) => {
           console.log(error);
         })
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

用英语讲:

  • 导入InjectFirebaseApp
  • 在您的组件中可用
  • 开始使用所有原生javascript SDK函数和方法,例如 sendPasswordResetEmail()

auth.使用可用的方法和功能执行a 不会自动完成,因此您可能需要与您关系密切的文档,例如:https://firebase.google.com/docs/auth/web/manage-users

谢谢?给@cartant:https://stackoverflow.com/a/39069813/1757321


Rob*_*man 6

我将尝试回答我自己的问题.我先说我确定我的答案不是最优雅的解决方案,我还不是javascript /打字稿/角度专家.但我的回答确实有效 - 即使我不完全理解.

我使用angular-cli来设置我的项目,该项目基于angular2和最新的firebase.显然,当您使用它来设置项目时,存在一个名为"firebase"的全局对象.在角度2组件中显示它的一种方法是将此声明放在组件的全局级别(在import语句之后和类声明之前).

declare var firebase : any;
Run Code Online (Sandbox Code Playgroud)

执行此操作后,可以在组件中使用全局firebase对象.

  • 您的解决方案有效,只有一行代码.对我来说似乎很优雅;-) (2认同)

Bjö*_*hel 6

RanchoSoftware的解决方案对我不起作用,我使用过

import {AngularFireModule} from "angularfire2";
import *as firebase from 'firebase';
Run Code Online (Sandbox Code Playgroud)

在app.module.ts文件中的导入内

在这里找到:https: //github.com/angular/angularfire2/issues/445