Angular 2.0 – real-time components using Firebase

In earlier post we saw how to build a hello world web component using Angular 2.0 beta.
Now we will create a real-time component using Firebase. We will have 2 components:

  1. adding elements in the list component
  2. listing all the elements component

To build the first component for adding elements in a list, we just need a simple HTML with 2 fields and a button, and some small JS method to send these fields to Firebase.

The add_message.ts:

import {Component} from 'angular2/core';
import {Message, MessagesService} from './messages_service';

@Component({
// Declare the tag name
selector: 'add-message',
template: `
<label>Name:</label>
<input type="text" [(ngModel)]="m.name" placeholder="Enter a name here">

<label>Message:</label>
<input type="text" [(ngModel)]="m.message" placeholder="Enter a message here">

<button type="button" (click)="sendMessage()">Send message</button>
`,
providers: [MessagesService]
})
export class AddMessage {
// Declaring the variable for binding with initial value
public m: Message = new Message();


constructor(private _MessagesService: MessagesService) { }

sendMessage() {
console.log("send message[" + this.m.name + "," + this.m.message + "]");
this._MessagesService.sendMessage(this.m);
}
}

For the second component, we will just need to iterate all the elements from the Firebase and display them using an unordered list. To iterate over the elements we will use the Angular *ngFor tag.

The list_messages.ts:

import {Component} from 'angular2/core';
import {Message, MessagesService} from './messages_service';

@Component({
// Declare the tag name
selector: 'list-messages',
template: `
<h1>Messages:</h1>
<ul>
	<li *ngFor="#message of messages">
{{message.name}} - {{message.message}}</li>
</ul>
`,
providers: [MessagesService]
})
export class ListMessages {

public messages: Message[];

constructor(private _MessagesService: MessagesService) { }

ngOnInit() {
this.messages = this._MessagesService.getMessages();
}
}

As we can see, for these 2 small components we have externalized the communication with Firebase.

The messages_service.ts:

import {Injectable, EventEmitter} from 'angular2/core';

export class Message {
  public key: string;
  public name: string;
  public message: string;

  constructor(name: string, message: string, key: string) {
    this.name = name;
    this.message = message;
    this.key = key;
  }
}

@Injectable()
export class MessagesService {
  private ref: Firebase;
  private refMessages: Firebase;    

  constructor() {

    console.log(&quot;constructor MessagesService&quot;);
    if (!this.ref) {
      this.ref = new Firebase(&quot;https://chat-with-2lc.firebaseio.com&quot;);
      this.refMessages = this.ref.child(&quot;messages&quot;);
    }

  }

   getMessages() {

      //delete old messages and the old listener
      promissedMessages = [];
      this.refMessages.off('child_added');

      //add Firebase listener on child added
      this.refMessages.on(&quot;child_added&quot;, function(snapshot, prevChildKey) {
        var name = snapshot.val().name;
        var message = snapshot.val().message;
        var key = snapshot.key();

        promissedMessages.push(new Message(name, message, key));
      });

    return promissedMessages;
  }

   sendMessage(m: Message) {
      this.refMessages.push({
          name: m.name,
          message: m.message
    });
  }

}

var promissedMessages: Message[] = [];

Since we can only bootstrap one component, we will use a wrapper over the add messages and list messages components. We will call it wrapper_messages, and it’s only scope will be to display the add_messages and list_messages components.

The wrapper_messages.ts:

import {Component} from 'angular2/core';
import {Message, MessagesService} from './messages_service';
import {AddMessage} from './add_message';
import {ListMessages} from './list_messages';

@Component({
// Declare the tag name
selector: 'messages-app_wrapper',
template: `
<add-message></add-message>

<hr>

<list-messages></list-messages>
`,
providers: [MessagesService],
directives: [ListMessages, AddMessage]
})
export class MessagesAppWrapper {

constructor(private _MessagesService: MessagesService) { }

}

We will bootstrap our component using main.ts:

import {bootstrap} from 'angular2/platform/browser';
import {MessagesAppWrapper} from './wrapper_messages';

bootstrap(MessagesAppWrapper);

You will observe that in the index.html we added a JS reference to Firebase in order for all the functions provided by our service to work.

<html>
<head>

<title>Hellow World Component</title>

<!-- 1. Load libraries -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
 <script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
 <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

<!-- 2. Configure SystemJS -->
<script>
 System.config({
 packages: { 
 app: {
 format: 'register',
 defaultExtension: 'js'
 }
 }
 });
 System.import('app/main')
 .then(null, console.error.bind(console));
 </script>

<!-- Include the Firebase js -->
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>

</head>

<!-- 3. Display the application -->
<body>
<messages-app_wrapper>Loading...</messages-app_wrapper>
</body>

</html>

You will find in the images bellow how the app will look like when you run it with “npm start” and Firebase console the messages that we have sent using it. Have fun developing your own real-time components using Firebase 🙂
ex_angular_firebase_01ex_angular_firebase_02

1 thought on “Angular 2.0 – real-time components using Firebase

Leave a comment