Firebase using Angular4 – Part 2

WP Post Author

firebase 1

Welcome back to “Learn Firebase: The Data Engineer Way” !! Hope you were looking forward to this. Happy Learning…

In previous blog, we have learned to create base template for our app using Firebase authentication. Please note that you can use blog-1 source code as base template for any Angular4 project which requires common functionalities like sign up, sign in & logout.

In this blog, we will learn to implement and manage features of inventory app which includes add/update/delete of an inventory item.

MOCKUP

manage

DATA MODELING

Lets create data model as per mock up. Lets list down fields of single item.
  • Name : String
  • Serial Number : String
  • Category: String
  • Cost: Numeric
  • Currency: String
  • Available: Items
  • Purchase Date: Date
  • Comments: Text

Basic rule of Firebase, which is also mentioned in Firebase documentation, is to keep data structure flat i.e. no or minimal nesting. I haven’t tried deep nesting in Firebase but as per my experience, I can say it will make data retrieval slower.

Note: Ignore ‘Key’ field for now, we will cover that shortly.

Again, Firebase stores this data as JSON object. Firebase database is nothing but a large nested json object. The rows shown in mock up are stored in Firebase database as shown below –

manage db

Inventory-app-726af is a root node. I am storing all inventory item objects under node named ‘items’. So we have to insert any object in Firebase under either root node in our case ‘Inventory-app-726af’ or under any parent node like ‘items’.

Whenever we add/insert or in Firebase’s terms push object into Firebase database, Firebase assign an unique key to object (you can think of it as ObjectID in MongoDB or Auto Increment PK in Mysql).

TYPESCRIPT OBJECT

The corresponding typescript object would be:

  1. export class Item {
  2. public name: string;
  3. public cost: number;
  4. public totalItems: number;
  5. public availableItems: number;
  6. public purchaseDate: Date;
  7. public $key: string;
  8. public serialNum: string;
  9. public category: string;
  10. public comments: string;
  11. public currency: string;
  12.  
  13. constructor(serialNum: string,name: string, cost: number, totalItems: number
  14. , purchaseDate: Date, category: string, currency: string, comments: string) {
  15. this.name = name;
  16. this.cost = cost;
  17. this.totalItems = totalItems;
  18. this.serialNum = serialNum;
  19. this.purchaseDate = purchaseDate;
  20. this.category = category;
  21. this.currency = currency;
  22. this.comments = comments;
  23. }}

INVENTORY SERVICE

  1. import { Injectable } from '@angular/core';
  2. import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
  3. import { AngularFireAuth } from 'angularfire2/auth';
  4. import { Item } from './inventory.model';
  5.  
  6. @Injectable()
  7. export class InventoryService{
  8. item: Item ;
  9. items: FirebaseListObservable<any[]>;
  10. constructor(private db: AngularFireDatabase) {
  11. this.items = this.db.list('/items');
  12. }
  13. getAllItems() {
  14. return this.items.map(
  15. (data) => data.map(x => x as Item)
  16. );
  17. }
  18. deleteItemByKey($key: string) {
  19. this.items.remove($key);
  20. }
  21. addItem(item: Item) {
  22. this.items.push(item);
  23. }
  24. editItem(key: string,item: Item) {
  25. this.db.object('items/'+key).update(item);
  26. }
  27. }

AngularFireDatabase (variable db) provides two methodes to refer firebase database object.

db.list – It means we are refering to an array list i.e. node which is referred in list method is going to return array list.

e.g. db.list(‘/items’) – have list of objects db.object – It means we are referring to single object i.e. node which is referred in object method is going to return an object.
e.g. db.object(‘/items/-Kmb-ZXfao7VdfenhfYj’) – refers to Notepads-4 object

Using above two methods we can then accomplish any CRUD operation as shown below.

Create Item

  1. db.list(/items’).push(itemObject);
Think of an array and you want to add an element. So you will use push method

Read Items

  1. db.list(/items’)

This will return items. I generally use map method to cast raw object into Item object.

Update Item

  1. db.object(/items/-Kmb-ZXfao7VdfenhfYj’).update(newItem)

To update specific item, you first have to locate that item and then update with new value.

Delete Item

Similar to push, if we want to delete an item for array list, we can use remove method.

HTML CODE

Kindly refer manage.component.html file. This is just a boiler plate code to add/edit forms and pass those values to services. I have install two npm modules
  1. npm install ng2-bootstrap-modal
  2. npm install ng2-bootstrap
Above modules makes life easier while handling form requests.

TYPESCRIPT CODE

  1. export class ManageComponent implements OnInit {
  2.  
  3. itemList: Item[] = [];
  4. selectedItem: Item;
  5. @ViewChild('addItemModal') public addItemModal: ModalDirective ;
  6. @ViewChild('editItemModal') public editItemModal: ModalDirective ;
  7.  
  8. constructor(private inventoryService: InventoryService) {
  9. inventoryService.getAllItems().subscribe(
  10. data => this.itemList = data
  11. );
  12. }
  13. ..
  14. ..
  15. }

Major things to notice in above typescript code are:

@ViewChild

To get access to a component and its methods, we can use the @ViewChild decorator. We are accessing both input forms ‘addItemModal’ and ‘editItemModal’ through @ViewChild feature.

Observable

Observables open up a continuous channel of communication in which multiple values of data can be emitted over time.

If you check getAllItems method code in inventory.service.ts, it returns observable. So to get data from obseravable, we have to subscribe it.

This is where Firebase becomes real-time. Whenever any user add or update or delete inventory item, getAllItems returns updated list of items through websocket.

Hope this blog helps you learn to implement and manage the features of inventory app.If you have any queries or need further clarification on any section of the blog , please write us in comment section.

In next blog, we will implement Request and Approve functionality where we will learn how to perform Firebase joins. Keep checking this space for new Blog.