Skip to content

Instantly share code, notes, and snippets.

@matthamil
Last active November 21, 2016 03:47
Show Gist options
  • Save matthamil/a4a96219b353e255f3125daa5bc08638 to your computer and use it in GitHub Desktop.
Save matthamil/a4a96219b353e255f3125daa5bc08638 to your computer and use it in GitHub Desktop.
Websockets with Angular 1 and Firebase
// First, you need a reference to your DB using the Firebase SDK
// Include <script src="path/to/firebase.js"> in index.html OR
// import firebase from 'firebase' if using a module loader like Browserify/Webpack/etc
// const DATABASEREF = firebase.database().ref(`endpoint/you/want/to/connect/to`);
// The endpoint you want to connect to is YOUR-FIREBASE-URL/<endpoint>
// I use a capital letter variable name to denote that this var (1) won't change (2) is super important so I can easily find it in my code.
// Reference to myapp-firebase.io/messages.json
const DATABASEREF = firebase.database().ref(`messages`);
// Listen to database updates at that specific location
// The callback fn executes any time the value at that location in Firebase changes
DATABASEREF.on('value', (snapshot) => {
// The argument passed into the cb fn has a method on it called .val() that needs to be called to access the data returned from the websocket
// OPTIONAL: capturing the FB Key in case the data received is nested and I need it to dig into the object
const key = Object.keys(snapshot.val())[0]; // read above comment, this isn't necessary, BUT its useful if your data is nested
// const nestedData = snapshot.val()[key];
const messages = snapshot.val();
$scope.messages = messages;
$scope.$apply(); // forces Angular to know that changes to $scope have occured
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment