Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active May 7, 2019 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codediodeio/1811a76a4aa125b781334859b68cbf1c to your computer and use it in GitHub Desktop.
Save codediodeio/1811a76a4aa125b781334859b68cbf1c to your computer and use it in GitHub Desktop.
Associate Firebase users with database items based on their UID
"rules": {
"items": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
/// Data Structure in Firebase
// -|items
// -|userID
// -|itemId
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Item } from './item';
import { AngularFireAuth } from 'angularfire2/auth';
@Injectable()
export class ItemService {
items: FirebaseListObservable<Item[]> = null; // list of objects
userId: string;
constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
})
}
// Return an observable list with optional query
// You will usually call this from OnInit in a component
getItemsList(query={}): FirebaseListObservable<Item[]> {
if (!this.userId) return;
this.items = this.db.list(`items/${this.userId}`, {
query: query
});
return this.items
}
// Create a bramd new item
createItem(item: Item): void {
this.items.push(item)
.catch(error => this.handleError(error))
}
// Update an exisiting item
updateItem(key: string, value: any): void {
this.items.update(key, value)
.catch(error => this.handleError(error))
}
// Deletes a single item
deleteItem(key: string): void {
this.items.remove(key)
.catch(error => this.handleError(error))
}
// Deletes the entire list of items
deleteAll(): void {
this.items.remove()
.catch(error => this.handleError(error))
}
// Default error handling for all actions
private handleError(error) {
console.log(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment