Firebase variable that can be accessed globally

In my ionic 1 app I had the following global variable in the app.js file

/* FIREBASE */
var fb = new Firebase("https://brilliant-inferno-1044.firebaseio.com");

From the factories.js I was able to reference it as follows: ref = fb.child("houses");

How can I do the same in ionic 2? Should it live in the constructor of the class for the app.js file in ionic2?

this.firebaseUrl = "https://brilliant-inferno-1044.firebaseio.com"; (maybe?)

I’m not that experienced with Ionic/Angular 2 yet but the way I do that at the moment is by creating a class with a static property that I can call from anywhere.

class AppConfig { 

static fb = new Firebase("http://yourURLhere");

}

Then call it from your other components by importing AppConfig class and calling the property this way:

AppConfig.fb

Do you create a new file “AppConfig.js” (for example) where you add the AppConfig class? Or do you add the class to an existing file?

Doesn’t matter.

But if you create a new file make sure to export the class so you can import it from elsewhere.

For organizational reasons I would create a new file to store that class in.

Also since you would like to call that class and it’s properties from other components that are in different files, then you do need to have a separate file.

Awesome. I’ll give it a try. Thanks for your help!

No problem let me know if you need any further help

If you are using Angular2 --> read about injectables (it is something like services in Angular 1). :wink:

They are an easy way to provide functions and properties to all components

I checked them out but I didn’t understand how is it different than just having a regular class?

I’m not sure if I do this the right way or not (I’d be interested to know) but I have a config.js file named:

providers/config.js

In there I export some constants e.g

export let URL_GOOGLE = "https://www.google.co.uk";
export let URL_BBC = "https://www.bbc.co.uk";

and then in any components I want to use them I do:

import {URL_GOOGLE} from '../providers/config';

and then just use that value in the component.

As I said, I have no idea is this is best practice or not?

1 Like