Skip to content

Document properly how to use multiple Firebase projects in one app #1305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
swftvsn opened this issue Oct 24, 2017 · 8 comments
Closed

Document properly how to use multiple Firebase projects in one app #1305

swftvsn opened this issue Oct 24, 2017 · 8 comments

Comments

@swftvsn
Copy link

swftvsn commented Oct 24, 2017

There's a lenghty discussion about this in #1240, and one stackblitz example how to do it, thanks for that!

The comments keep piling, so it seems this is still a source of frustration to people.

The documentation should include examples how to...

  • Configure 2 or more projects (for an example projects a, b and c)
  • inject realtime database or firestore pointing to project b to Angular component
  • inject realtime database or firestore pointing to project c to Angular service (annotated with @Injectable())
  • inject two instances of realtime database or firestore pointing to project b and c configuration to Angular component
  • inject two instances of realtime database or firestore pointing to project b and c configuration to Angular service (annotated with @Injectable())

So, essentially how to inject like this:

import { Injectable } from '@angular/core'
import { AngularFireDatabase } from 'angularfire2/database'

@Injectable()
export class MyService {

  constructor(
    private storeAppDb: AngularFireDatabase,
    private invoicingAppDb: AngularFireDatabase
  ) {
  }

}

I don't think Angular supports injection scheme like that, but a blueprint how to achieve the same would be nice. (If I can choose which one to inject, then I can make two wrapper services, that I can inject..)

It would be nice though to be just able to say:

import { Injectable } from '@angular/core'

@Injectable()
export class MyService {

  constructor(
    private angularfire: AngularFire
  ) {
    const firestore1 = angularfire.firestore('conf1')
    const firestore2 = angularfire.firestore('conf2')
  }

}

which would return the angularfireified firestore etc. services.

@ghost
Copy link

ghost commented Oct 25, 2017

merci :)

@james11a
Copy link

@swftvsn My solution is implemented in an Ionic application that I am working on.. This is tested and working (so far :) )

Below is my configuration:

Say the 2 Firebase application configuration variables are firebaseConfigA & firebaseConfigB with their names 'appA' & 'appB ' stored in firebaseAppNameA & firebaseAppNameB.

Note: It is recommended that all such configuration variables are stored in a separate configuration file / custom webpack environment files. The variables will be imported wherever required from here. In my case, I have custom webpack environment setup.
If you need help with setting up environments using custom webpack for Ionic, check out this fantastic post from @gshigeto: https://github.com/gshigeto/ionic-environment-variables

Initializing the Firebase applications in your application's ngModule is not required as this will now be done through a service as shown below.

To the code...

All my Firebase related function are handled in a separate service:

firebase.service.ts

/** Angular imports */
import { Injectable } from "@angular/core";

/** 3rd-party imports */
import { AngularFireDatabase, AngularFireList, AngularFireObject } from "angularfire2/database";
import { _firebaseAppFactory } from "angularfire2/firebase.app.module";
import { FirebaseAppConfig } from "angularfire2";

@Injectable()
export class FirebaseService {
    private _db: AngularFireDatabase;

    constructor() { }

    /** Function to initialize firebase application and
     * get DB provider for the corresponding application.
     */
    public initFirebaseApp(config: FirebaseAppConfig, firebaseAppName: string) {
        this._db = new AngularFireDatabase(_firebaseAppFactory(config, firebaseAppName));
    }

    /** Function to get firebase DB list */
    public getList(path: string): AngularFireList<{}> {
        return this._db.list(path);
    }

    /** Function to get firebase DB object */
    public getObject(path: string): AngularFireObject<{}> {
        return this._db.object(path);
    }
}

Import the above service in your application's ngModule.

Now, using the service in a component where I connect to both applications:

home.component.ts

// ... do all required imports
import {
    firebaseConfigA, firebaseAppNameA,
    firebaseConfigB, firebaseAppNameB
} from "@app/env";
import { FirebaseService } from "../../services/firebase.service";

@Component({
    selector       : "page-home",
    templateUrl    : "home.html"
})
export class ScannerDemoPage implements OnInit {
    constructor(private _firebaseService: FirebaseService) { }
    
    ngOnInit() {
        // Initialize 1st application
        this._firebaseService.initFirebaseApp(firebaseConfigA, firebaseAppNameA);
        let myList = this._firebaseService.getList("/path1");

        // Initialize 2nd application
        this._firebaseService.initFirebaseApp(firebaseConfigB, firebaseAppNameB);
        let myObj = this._firebaseService.getObject("/path2");
    }
}

Hope this helps.

@ghost
Copy link

ghost commented Feb 24, 2018

hi,
please do you have same solution for firestore collection ?

thanks you

@ghost
Copy link

ghost commented Feb 24, 2018

capture d ecran de 2018-02-24 22-13-21
capture d ecran de 2018-02-24 22-13-49

i try to use multiple config :
list.ts :

@component({
selector: 'page-list',
templateUrl: 'list.html',
providers: [
{ provide: FirebaseAppName, useValue: 'courses' },
{ provide: FirebaseAppConfigToken, useValue: firebaseClient },
{ provide: AngularFireModule, useValue: 'courses' },
FirebaseAppProvider
]
})
export class ListPage {
todoCollectionRef: AngularFirestoreCollection;
todo$: Observable<Todo[]>;

constructor(private afs: AngularFirestore, public app: FirebaseApp) {
this.todoCollectionRef = this.afs.collection('articles');
this.todo$ = this.todoCollectionRef.valueChanges();
console.log(app.name)
console.log(app.options)
}

}

source :

https://stackblitz.com/edit/angular-aw3pyc

"angularfire2": "^5.0.0-rc.6",
"firebase": "^4.10.1",
only the collection from app..module.ts : AngularFireModule.initializeApp(firebaseDemo, 'firebaseDemo'), is loaded by the pages ?!

thanks you

@jamesdaniels
Copy link
Member

#1026

@fbayanati
Copy link

fbayanati commented Aug 20, 2018

Also you may look into this stalkblitz,
Or the stackoverflow item in case you may thinking about Firestore.

@newmesiss
Copy link

@fbayanati this works well, I implemented it in my project and it goes well, but how do I integrate the session start of the second database?

@joel1725
Copy link

joel1725 commented May 9, 2019

Mi solución se implementa en una aplicación Ionic en la que estoy trabajando. Esto está probado y funcionando (hasta ahora :))

A continuación se muestra mi configuración:

Supongamos que las 2 variables de configuración de la aplicación Firebase son firebaseConfigA & firebaseConfigB con sus nombres ' appA ' y ' appB ' almacenados en firebaseAppNameA & firebaseAppNameB .

Nota: Se recomienda que todas estas variables de configuración se almacenen en un archivo de configuración separado / archivos de entorno de paquete web personalizado. Las variables serán importadas donde sea necesario desde aquí. En mi caso, tengo la configuración personalizada del entorno webpack.
Si necesita ayuda para configurar entornos con un paquete web personalizado para Ionic, consulte esta fantástica publicación de @gshigeto : https://github.com/gshigeto/ionic-environment-variables

No es necesario inicializar las aplicaciones Firebase en el ngModule de su aplicación, ya que esto se hará a través de un servicio como se muestra a continuación.

Al código ...

Todas mis funciones relacionadas con Firebase se manejan en un servicio separado:

firebase.service.ts

/** Angular imports */
import { Injectable } from "@angular/core";

/** 3rd-party imports */
import { AngularFireDatabase, AngularFireList, AngularFireObject } from "angularfire2/database";
import { _firebaseAppFactory } from "angularfire2/firebase.app.module";
import { FirebaseAppConfig } from "angularfire2";

@Injectable()
export class FirebaseService {
    private _db: AngularFireDatabase;

    constructor() { }

    /** Function to initialize firebase application and
     * get DB provider for the corresponding application.
     */
    public initFirebaseApp(config: FirebaseAppConfig, firebaseAppName: string) {
        this._db = new AngularFireDatabase(_firebaseAppFactory(config, firebaseAppName));
    }

    /** Function to get firebase DB list */
    public getList(path: string): AngularFireList<{}> {
        return this._db.list(path);
    }

    /** Function to get firebase DB object */
    public getObject(path: string): AngularFireObject<{}> {
        return this._db.object(path);
    }
}

Importe el servicio anterior en el ngModule de su aplicación.

Ahora, usando el servicio en un componente donde me conecto a ambas aplicaciones:

home.component.ts

// ... do all required imports
import {
    firebaseConfigA, firebaseAppNameA,
    firebaseConfigB, firebaseAppNameB
} from "@app/env";
import { FirebaseService } from "../../services/firebase.service";

@Component({
    selector       : "page-home",
    templateUrl    : "home.html"
})
export class ScannerDemoPage implements OnInit {
    constructor(private _firebaseService: FirebaseService) { }
    
    ngOnInit() {
        // Initialize 1st application
        this._firebaseService.initFirebaseApp(firebaseConfigA, firebaseAppNameA);
        let myList = this._firebaseService.getList("/path1");

        // Initialize 2nd application
        this._firebaseService.initFirebaseApp(firebaseConfigB, firebaseAppNameB);
        let myObj = this._firebaseService.getObject("/path2");
    }
}

Espero que esto ayude.

Hi @james11a

Could you give me an example project of this that you put here, the truth is that I have 4 days and still can not find how to place it correctly, I would like to find the solution since I have an app that needs the integration of three firestore projects and I do not own the complete experience to understand how you have solved it, I would really appreciate it if you could provide me with something more detailed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants