Firebase using Angular4 – Part 2

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

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 –

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. constructor(serialNum: string,name: string, cost: number, totalItems: number

  13. , purchaseDate: Date, category: string, currency: string, comments: string) {

  14. this.name = name;

  15. this.cost = cost;

  16. this.totalItems = totalItems;

  17. this.serialNum = serialNum;

  18. this.purchaseDate = purchaseDate;

  19. this.category = category;

  20. this.currency = currency;

  21. this.comments = comments;

  22. }}

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. @Injectable()

  6. export class InventoryService{

  7. item: Item ;

  8. items: FirebaseListObservable<any[]>;

  9. constructor(private db: AngularFireDatabase) {

  10. this.items = this.db.list('/items');

  11. }

  12. getAllItems() {

  13. return this.items.map(

  14. (data) => data.map(x => x as Item)

  15. );

  16. }

  17. deleteItemByKey($key: string) {

  18. this.items.remove($key);

  19. }

  20. addItem(item: Item) {

  21. this.items.push(item);

  22. }

  23. editItem(key: string,item: Item) {

  24. this.db.object('items/'+key).update(item);

  25. }

  26. }

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. itemList: Item[] = [];

  3. selectedItem: Item;

  4. @ViewChild('addItemModal') public addItemModal: ModalDirective ;

  5. @ViewChild('editItemModal') public editItemModal: ModalDirective ;

  6. constructor(private inventoryService: InventoryService) {

  7. inventoryService.getAllItems().subscribe(

  8. data => this.itemList = data

  9. );

  10. }

  11. ..

  12. ..

  13. }

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.