How To Implement Angular + Firebase Database NoSQL Relationship
What Will I Learn
In this Tutorial I'm going to teach you about ways to associate firebase users with data in the real time database on Our Angular Project I'll go over three different methods and when to use them and also talk about ways to keep them secure on the backend.
Requirements
- Installed Angular CLI On Your Computer
- Basic Javascript Knowledge
- Basic Html + Javascript Knowledge
Difficulty
- Intermediate
Tutorial Content
Before we get into our code editor it's important to go over a couple know SQL database
design best practices if you come from a SQL background you're used to designing a database that is completely
centered around relationships. In No SQL we care less about relationships and more about the efficiency of the actual query that we're making consider a database design it has everything nested under the user ID if you wanted to loop over just the users and display
their user name you'd also have to load all the nested data further down the tree which would become very inefficient.
If you have a lot of Records a better way to handle this is to keep the data shallow so you only query for the actual data you need now we can start building
some user relationships with firebase and angular for the first method works by nesting a user's item under their own user ID.
This is ideal when you're showing data that's organized by user for example a Twitter feed.
Here we have an item service and we're going to import both the angularfire database and
the angularfire auth module.
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
Then we create an item class which represents our data at this point with just one
body string attribute this class will be returned to us as an angular fire list observable when we inject the service we want to subscribe to the angularfire
off state and we'll set the user ID returned from that off state to the user ID on the service.
This allows us to make queries based on that currently logged in users ID.
items: FirebaseListObservable<Item[]> = null;
userId: string;
constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
})
}
Now that we have the user ID we can hit the database for the list that is nested under that user ID if it's undefined we just return null it's defined we interpolate it into the path to the database
getItemsList(): FirebaseListObservable<Item[]> {
if (!this.userId) return;
this.items = this.db.list(`items/${this.userId}`);
return this.items
}
If we want to create a new item it's as simple as pushing another item object onto this list observable
createItem(item: Item) {
this.items.push(item)
}
If we back in the app web page , if there is not an error we can see that when we create a
new item it's nested under that users user ID as expected. If we logout and login with a different user we shouldn't
see any items in the feed which we don't. And if we create a new item with this user their data is nested under their user ID essentially separating the data by user
This works great on the our front-end web application. But we also need to secure the backend data with a firebase database rule. In this example we match the user ID . The data is nested under with the actual off ID and firebase.
{
"rules":{
".read" : true,
".write : false",
"items" : {
"$uid" : {
".write": "auth.uid === $uid "
}
}
}
}
If it's a match then we allow the write operation to take place a second way to associate
users with items is to save the user ID.
Item Query
As an attribute on the item itself this approach is useful when you need the association. But you're not querying by the user for example comments on a blog post or something similar.
We can make this work by modifying three lines of code first we add a user ID to the item class.
export class Item {
body: string;
userId: string;
}
Then we set that user ID on the item when it's created then we remove the user ID from the database path.
Because we're no longer nesting under the user ID.
getItemsList(): FirebaseListObservable<Item[]> {
if (!this.userId) return;
this.items = this.db.list(`items/`);
return this.items
}
Back in the app we create a new item and we can see that user ID is on the item itself. And if we create another item
with a different user we should have a different user ID on that item but still both items are coming up in the feed now
in firebase we can see the user ID attribute is on each item.
To secure the backend we see if the existing data in the database has a matching user ID and we also allow the write to occur if it's null because that means the users.
Membership
Creating a new item the third scenario is when you have items that can be associated with multiple users. In this
case we create a collection of members that are nested under the item ID and the key for each member is that users
user ID back in the service will create a new function to join an item passing at the items key as an argument.
the data will be the user ID for the key set to true we return the current members as an object observable then
update that observable with the new data.
join(itemKey) {
const data = { [this.userId]: true}
const members = this.db.object(`items/${itemKey}/members`)
members.update(data)
}
To leave an item we follow the same basic approach we query for an object observable with the current user ID and if it exists we remove it
leave(itemKey) {
const member = this.db.object(`items/${itemKey}/members/${this.userId}`)
member.remove()
}
Back in the app we create a new item that defaults to no members and then we can click the join button which will add
that user ID to the list of members.
When we log in with a different user we should see that they can also add their
user ID to this item. Going into firebase we can see that the members collection on this item.
it's updated with the key after each button is clicked.
That's it my lesson for this tutorial if you found some question you can ask me on the comment section and I'll see you next time
Posted on Utopian.io - Rewarding Open Source Contributors

Your contribution cannot be approved because it does not follow the Utopian Rules.
The code is outdated and already available online for older versions of AngularFire.
You can contact us on Discord.
[utopian-moderator]
Hey @deathwing, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!
nice post sir thanks for sharing.....
Thanks for support dont forget to follow me for keep and touch . If you have any question please write in this comment section :)