Getting started with deepstreamHub is easy and takes less than ten minutes. However, if you have any questions, please get in touch.
This getting started guide will walk you through integrating deepstream in Angular (v2x). You will also learn how to implement the three deepstream core concepts: Records, Events and RPCs.
First, let's start by creating a free deepstreamHub account:
Create a free account and get your API key
deepstream provides a JavaScript library which helps in interacting with your deepstreamHub server.
Create an Angular App
Install the Angular CLI tool globally and use the tool to scaffold a new app:
# Install CLI tool
npm install -g @angular/cli
# Scaffold a new app
ng new ds-angular
Connect to deepstreamHub and log in
After you have successfully created an Angular app install the deepstream and the JS-client library in your new project:
npm install deepstream.io-client-js --save
To tell Angular that the installed dependency is a vendor file and should be loaded accordingly, add deepstream script to the scripts
array in ./angular-cli.json
:
. . .
"scripts": [
"../node_modules/deepstream.io-client-js/dist/deepstream.js"
],
. . .
The JS library exposes a method, deepstream
. Calling deepstream
from nowhere might throw an error. You can avoid that by declaring a type just after the imports:
import { Component, OnInit } from '@angular/core';
// Type deepstream with any
declare var deepstream:any;
Get your app url from the dashboard and establish a connection to deepstreamHub using an Angular service:
@Injectable()
export class DsService {
get dsInstance() {
return deepstream('<YOUR APP URL>').login()
}
}
The login
method can take credentials if authentication is configured.
Records (realtime datastore)
Records are the documents in deepstreamHub’s realtime datastore. A record is identified by a unique id and can contain any kind of JSON data. Clients and backend processes can create, read, write, update and observe the entire record as well as paths within it. Any change is immediately synchronized amongst all connected subscribers.
Records can be arranged in lists and collections and can contain references to other records to allow for the modelling of relational data structures.
You can learn more about records in the records tutorial.
var myRecord = ds.record.getRecord( 'test/johndoe' );
Values can be stored using the .set()
method
myRecord.set({
firstname: 'John',
lastname: 'Doe'
});
Let's set up two-way bindings with an input field - whenever a path within our record, e.g. firstname
changes we want to update the input. Whenever a user types, we want to update the record.
Let's see a contexual example:
@Component({
selector: 'my-record',
template: `
<div class="group realtimedb">
<h2>Realtime Datastore</h2>
<div class="input-group half left">
<label>Firstname</label>
<input type="text" id="firstname" [ngModel]="firstname" (ngModelChange)="handleFnameChange($event)" />
</div>
<div class="input-group half">
<label>Lastname</label>
<input type="text" id="lastname" [ngModel]="lastname" (ngModelChange)="handleLnameChange($event)" />
</div>
</div>
`
})
export class RecordComponent implements OnInit{
firstname;
lastname;
record;
constructor(private dsService: DsService){}
ngOnInit() {
this.record = this.dsService.dsInstance.record.getRecord('test/johndoe')
this.record.subscribe((val) => {
this.firstname = val.firstname;
this.lastname = val.lastname;
})
}
handleFnameChange(val){
this.record.set('firstname', val);
}
handleLnameChange(val) {
this.record.set('lastname', val);
}
}
The subscribe
method is used to listen for updates and update the inputs accordingly. The method is called in the ngOnInit
lifecycle hook so it can be setup once the component is loaded.
Events (publish-subscribe)
Events are deepstreamHub’s publish-subscribe mechanism. Clients and backend processes can subscribe to event-names (sometimes also called “topics” or “channels”) and receive messages published by other endpoints.
Events are non-persistent, one-off messages. For persistent data, please use records.
Clients and backend processes can receive events using .subscribe()
ds.event.subscribe( 'test-event', function( eventData ){ /*do stuff*/ });
... and publish events using .emit()
ds.event.emit( 'test-event', {some: 'data'} );
A little example:
@Component({
selector: 'my-events',
template: `
<div class="group pubsub">
<div class="half left">
<h2>Publish</h2>
<button class="half left" id="send-event" (click)="handleClick()">Send test-event with</button>
<input type="text" class="half" id="event-data" [(ngModel)]="value"/>
</div>
<div class="half">
<h2>Subscribe</h2>
<ul id="events-received">
<li *ngFor="let event of eventsReceived"></li>
</ul>
</div>
</div>
`
})
export class EventsComponent implements OnInit {
value = '';
eventsReceived = [];
constructor(private dsService: DsService){}
ngOnInit() {
this.dsService.dsInstance.event.subscribe('test-event', (val) => {
this.eventsReceived.push(val);
})
}
handleClick() {
console.log(this.value)
this.dsService.dsInstance.event.emit('test-event', this.value);
}
}
An event is published anytime the button is clicked and the event.subscribe
method listens for this publish action.
RPCs (request-response)
Remote Procedure Calls are deepstreamHub’s request-response mechanism. Clients and backend processes can register as “providers” for a given RPC, identified by a unique name. Other endpoints can request said RPC.
deepstreamHub will route requests to the right provider, load-balance between multiple providers for the same RPC, and handle data-serialisation and transport.
You can make a request using .make()
ds.rpc.make( 'multiply-numbers', { a: 6, b: 7 }, function( err, result ){
//result === 42
});
and answer it using .provide()
ds.rpc.provide( 'multiply-numbers', function( data, response ){
resp.send( data.a * data.b );
});
For example:
@Component({
selector: 'my-rpc',
template: `
<div class="group reqres">
<div class="half left">
<h2>Request</h2>
<button class="half left" id="make-rpc" (click)="handleClick()">Make multiply request</button>
<div class="half">
<input type="text" id="request-value" class="half left" value="3" [(ngModel)]="requestValue"/>
<span class="response half item" id="display-response"></span>
</div>
</div>
<div class="half">
<h2>Response</h2>
<div class="half left item">Multiply number with:</div>
<input type="text" value="7" class="half" id="response-value" [(ngModel)]="responseValue" />
</div>
</div>
`
})
class RPCComponent implements OnInit {
requestValue = '3';
responseValue = '7';
displayResponse = '-';
constructor(private dsService: DsService){}
handleClick() {
var data = {
value: parseFloat(this.requestValue)
};
this.dsService.dsInstance.rpc.make( 'multiply-number', data, ( err, resp ) => {
//display the response (or an error)
this.displayResponse = resp || err.toString();
});
}
ngOnInit() {
this.dsService.dsInstance.rpc.provide( 'multiply-number', ( data, response ) => {
// respond to the request by multiplying the incoming number
// with the one from the response input
response.send( data.value * parseFloat(this.responseValue) );
})
}
}
Clicking the button makes a request using rpc.make
. The .make
method is also responsible for handling the responses when they come back from the response provider which is the rpc.provide
method.
The three components can be assembled together into an app using the App
component:
@Component({
selector: 'my-app',
template: `
<div class="group connectionState">
Connection-State is: <em id="connection-state"></em>
</div>
<my-record></my-record>
<my-events></my-events>
<my-rpc></my-rpc>
`
})
class AppComponent implements OnInit{
connectionState = 'INITIAL';
constructor(private dsService: DsService){}
ngOnInit() {
this.dsService.dsInstance.on( 'connectionStateChanged', ( connectionState ) => {
this.connectionState = connectionState;
});
}
}
You also need to tell Angular about the modules you imported, the services you are injecting, the components you declared and the component you intend to bootstrap the app with using NgModule
:
@NgModule({
declarations: [
AppComponent,
RecordComponent,
EventsComponent,
RPCComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [
DsService
],
bootstrap: [AppComponent]
})
class AppModule { }
Where to go next?
To learn how to use deepstreamHub with other frontend frameworks head over to the tutorial section. To learn how to use the JavaScript SDK with NodeJS rather than in a browser, head over to the getting started with NodeJS tutorial.