且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问同一 Firebase 应用项目的多个实时数据库

更新时间:2023-11-22 16:56:58

我知道你在这里得到了有效的答案:https://github.com/angular/angularfire2/issues/1567

I know you got a working answer here : https://github.com/angular/angularfire2/issues/1567

测试:angularfire2":^5.0.0-rc.6.0",firebase":^4.12.1"

tested with : "angularfire2": "^5.0.0-rc.6.0", "firebase": "^4.12.1"

受我想分享的 #1567 启发,我构建了一个简约的包装器.使用多个数据库有两种不同或相同项目的方法.

I've built a minimalist wrapper inspired of the #1567 I'd like to share. There are 2 methods with different or same project to use multiple databases.

您可能会使用第一个,我不太明白在多个项目中使用多个数据库的意义.

You'll probably use the first one, I don't really understand the point of using multiple databases within multiple project.

@Injectable()
export class AngularFireWrapper {

  // Default database 
  private _firebaseDb = this.afDb.database;

  constructor(private afDb: AngularFireDatabase,
              @Optional() dbName: string) {

    console.log('Hello AngularFireWrapper, db :', dbName || 'default');

    // 1st Method, same project, same auth
    // environment.dbUrls = {
    //   ...
    //   otherDb: 'https://DB_NAME_SAME_PROJECT.firebaseio.com/'
    // }

    if (dbName && environment.dbUrls[dbName]) {
      const app: any = this.afDb.app;
      this._firebaseDb = app.database(environment.dbUrls[dbName]);
    }

    // 2nd Method, other project, different auth =/
    // environment.dbConfigs = {
    //   ...
    //   otherDb: {...} // usual firebase configs 
    // }

    if (dbName && environment.dbConfigs[dbName]) {
      this._firebaseDb = firebase.initializeApp(environment.dbConfigs[dbName], dbName)
        .database();
    }
  }

  db(dbName): AngularFireWrapper {
    return new AngularFireWrapper(this.afDb, dbName);
  }

  object(path: string): AngularFireObject<any> {
    const ref = this._firebaseDb.ref(path);
    return this.afDb.object(ref);
  }

  list(path: string, queryFn?: QueryFn): AngularFireList<any> {
    const ref = this._firebaseDb.ref(path);
    return this.afDb.list(ref, queryFn);
  }
}

复制粘贴,像通常使用自定义服务一样注入它,然后:

Copy-Paste, inject it as you usually do with your custom services and then :

export class MyApp {
  constructor(private afW: AngularFireWrapper) {

    this.afW.object('test')
      .valueChanges()
      .subscribe(console.log)
    // => output default db values

    this.afW.db('otherDb').object('test')
      .valueChanges()
      .subscribe(console.log)
    // => output otherDb values
  }