PubNub Angular2 SDK 1.3.2

Unsupported SDK

PubNub no longer supports this SDK, but you are welcome to contribute.

Get Code

https://github.com/pubnub/pubnub-angular2/releases

Get Code: CDN

Latest stable version

https://cdn.pubnub.com/sdk/pubnub-angular2/pubnub-angular2.1.3.2.js

Latest stable minified version

https://cdn.pubnub.com/sdk/pubnub-angular2/pubnub-angular2.1.3.2.min.js

Get Code: Source

https://github.com/pubnub/pubnub-angular2

Get Code: NPM

npm install --save pubnub pubnub-angular2

Get Code: Bower

bower install --save pubnub pubnub-angular2

Hello World

PubNub Angular2 is a wrapper for the PubNub JavaScript SDK that adds a few extra features to simplify integration with Angular v2 and v4.

  • Support: Available to use with TypeScript or plain JavaScript.
  • Events: Delegate methods accept the triggerEvents option which will broadcast certain callback and binding these directly to the HTML.
  • Autoload: An easy and fast way to retrieve history messages from your channel.
  • Multiple instance behavior: All instances are accessible throughout your application via the PubNub service.

You can also use the native PubNub JavaScript SDK if you feel it is more suitable for your situation.

How to use PubNubAngular for Angular4

npm install --save pubnub pubnub-angular2

There are two ways to register PubNubAngular in your list of providers in your Angular App: ngModules or ngComponents.

Using your ngModule

Angular Module lets you to use the same instance of PubNub in all Angular Components declared in this. Then you will not need to register PubNub in any Angular Component hosted by the Angular Module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PubNubAngular } from 'pubnub-angular2';
import { AppComponent } from './appComponent';
@NgModule({
imports:[ BrowserModule ],
declarations:[ AppComponent ],
providers:[ PubNubAngular ],
bootstrap:[ AppComponent ]
})
export class AppModule {
constructor() {}
}

Angular Component only lets you use the same instance of PubNub inside itself and its Angular Components children. For more information about this, refer to Dependency Injection and Hierarchical Dependency Injectors

import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>',
providers:[ PubNubAngular ]
})
export class AppComponent {
constructor() {}
}

Now, you can inject PubNubAngular into your ngComponents.

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
})
export class AppComponent {
constructor(pubnub: PubNubAngular) {
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});
}
}

How to use PubNubAngular for Angular2

For Angular2 you have to add some extra steps in order to setup the environment. Your HTML page will have to include the following libraries:

  • Global dependencies for Angular2
  • Angular2
  • PubNub JavaScript SDK
  • PubNub Angular2 SDK

With JavaScript, it is possible to use the libraries from CDN, NPM, and Bower.

  1. Include global dependencies for Angular2:

    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
  2. Include Angular2:

    <script src="node_modules/@angular/core/bundles/core.umd.js"></script>
    <script src="node_modules/@angular/common/bundles/common.umd.js"></script>
    <script src="node_modules/@angular/compiler/bundles/compiler.umd.js"></script>
    <script src="node_modules/@angular/platform-browser/bundles/platform-browser.umd.js"></script>
    <script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>
    <script src="node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>
  3. Include the latest version of the PubNub JavaScript SDK:

    <script src="node_modules/pubnub/dist/web/pubnub.js"></script>
  4. Include the PubNub Angular2 SDK:

    <script src="node_modules/pubnub-angular2/dist/pubnub-angular2.js"></script>

Integrate PubNub Angular2 SDK into your app with TypeScript

Your HTML page needs to include the libraries described above, but you need to load Angular2 and the PubNub Angular2 SDK from NPM modules.

  1. Include global dependencies for Angular2:

    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
  2. Include the latest version of the PubNub JavaScript SDK:

    <script src="node_modules/pubnub/dist/web/pubnub.js"></script>
  3. Include and load libraries from systemjs:

    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
    System.import('app').catch(function(err){
    console.error(err);
    });
    </script>

Angular2 uses systemjs.config.js. Include the following libraries inside the map attribute:

  • Rxjs
  • Angular2
  • PubNub Angular2 SDK

Your systemjs.config.js should look like this:

map: {
'rxjs': 'npm:rxjs',
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'pubnub-angular2': 'npm:pubnub-angular2/dist/pubnub-angular2.js'
}

Register the PubNub Angular2 SDK into Angular's list of Providers

There are two ways to register the PubNub Angular2 SDK in your app's list of providers: Angular Modules, and Components.

An Angular Module lets you use the same instance of PubNub in all Angular Components declared in the module. Then, you do not need to register PubNub in any Angular Component hosted by the Angular Module.

Registering inside an Angular Module using JavaScript
'use strict';

(function (app) {
app.appModule = ng.core.NgModule({
imports: [ng.platformBrowser.BrowserModule],
declarations: [app.appComponent],
providers: [ PubNubAngular ],
bootstrap: [app.appComponent]
}).Class({
constructor: function(){}
});

document.addEventListener('DOMContentLoaded', function(){
ng.platformBrowserDynamic.platformBrowserDynamic().bootstrapModule(app.appModule);
});
show all 16 lines
Registering inside an Angular Module using TypeScript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PubNubAngular } from 'pubnub-angular2';
import { AppComponent } from './appComponent';
@NgModule({
imports:[ BrowserModule ],
declarations:[ AppComponent ],
providers:[ PubNubAngular ],
bootstrap:[ AppComponent ]
})
export class AppModule {
constructor() {}
}

An Angular Component only lets to use the same instance of PubNub inside itself and its Angular Components children. For more information about this, refer to Dependency Injection and Hierarchical Dependency Injectors

Registering inside an Angular Component using JavaScript
(function (app) {
app.appComponent = ng.core.Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
providers: [ PubNubAngular ]
}).Class({
constructor: function () {}
});
})(window.app || (window.app = {}));
Registering inside an Angular Component using TypeScript
import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>',
providers: [PubNubAngular]
})
export class AppComponent {
constructor() {}
}

How to inject PubNubAngular

Registering PubNubAngular within the provider list in an Angular Module or Component lets you inject a PubNub instance into an Angular Component according to the Hierarchical Dependency then this will be a shared instance.

After injecting the PubNub instance in the Angular Component's constructor, initialize the service including the PUB_KEY and SUB_KEY. This process only has to be done once, since this instance is shared by all Angular Components within the same dependency scope.

Injecting an instance of PubNub using JavaScript
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

(function (app) {
app.appComponent = ng.core.Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
}).Class({
constructor: [PubNubAngular, function(pubnub){
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});
}]
});
})(window.app || (window.app = {}));
Injection an instance of PubNub using TypeScript
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
})
export class AppComponent {
constructor(pubnub: PubNubAngular) {
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});
}
}

Differences in usage with native JavaScript SDK

To learn about PubNub JavaScript features, refer to the PubNub JavaScript SDK documentation All methods of this SDK are wrapped with PubNubAngular

Native PubNub JavaScript SDK provides instance creation using Pubnub.init(), which returns a new instance with given credentials. In PubNub Angular2 SDK instances are hidden inside the service and are accessible via instance getters. Methods of default instance are mapped directly to the PubNub service, such as Pubnub.publish({...}). In most use cases, you can use only the default PubNub instance, but if you need multiple instances with different credentials, you should use the Pubnub.getInstance(instanceName) getter. In this case, the publish method is Pubnub.getInstance(instanceName).publish({}).

How to use the native PubNub JavaScript SDK

Native PubNub JavaScript SDK
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

var defaultInstance = new PubNub({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});

var anotherInstance = new PubNub({
publishKey: 'ANOTHER PUB_KEY',
subscribeKey: 'ANOTHER SUB_KEY'
});

defaultInstance.publish(
{
message: {such: 'Hello!'},
channel: 'my_channel'
},
show all 35 lines
Native PubNub JavaScript SDK using TypeScript
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

declare var PubNub: any;

var defaultInstance = new PubNub({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});

var anotherInstance = new PubNub({
publishKey: 'ANOTHER PUB_KEY',
subscribeKey: 'ANOTHER SUB_KEY'
});

defaultInstance.publish(
{
message: {such: 'Hello!'},
show all 37 lines

How to use PubNubAngular SDK

Using the PubNub Angular2 SDK with JavaScript
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

(function (app) {
app.appComponent = ng.core.Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
}).Class({
constructor: [PubNubAngular, function(pubnub){
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});

pubnub.getInstance("another").init({
publishKey: 'ANOTHER PUB_KEY',
subscribeKey: 'ANOTHER SUB_KEY'
});
show all 46 lines
Using the PubNub Angular2 SDK with TypeScript
Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.

import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';

@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
})

export class AppComponent {
constructor(pubnub: PubNubAngular) {
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});

show all 46 lines

That's it, you're ready to start using the PubNub Angular SDK.

Hello World Example

Hello World Example using JavaScript

(function (app) {
app.main_component = ng.core.Component({
selector: 'appComponent',
template: "<ul>" +
"<li *ngFor='let item of PubNub.getMessage(channel)'>{{item.message}}</li>" +
"</ul>"
}).Class({
constructor: [PubNubAngular, function(pubnub) {
this.channel = 'my_channel';
this.pubnub = pubnub;
this.pubnub.init({publishKey: 'YOUR PUB_KEY', subscribeKey: 'YOUR SUB_KEY'});
this.pubnub.subscribe({channels: [this.channel], triggerEvents: ['message']});
}],
ngOnInit: function () {
var self = this;
show all 22 lines

Hello World Example using TypeScript

import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';

@Component({
selector: "appComponent",
template: "<ul>" +
"<li *ngFor='let item of PubNub.getMessage(channel)'>{{item.message}}</li>" +
"</ul>"
})
export class AppComponent {
pubnub: PubNubAngular;
channel: string;
constructor(pubnub: PubNubAngular) {
this.channel = 'my_channel';
this.pubnub = pubnub;
show all 33 lines

Events

Another key feature of this SDK is the ability to trigger events in addition to passed in callbacks, getting the stack of all messages received and inject it directly in the HTML of your Angular Component. By default events will not be triggered.

To enable all possible events for certain methods, add triggerEvents:true option when you are subscribing a channels or channel groups.

Triggering and listening to events for the subscribe method

With JavaScript SDK V4, you can trigger 3 different events (message, presence and status).

Triggering the events:

pubnub.subscribe({
channels : ['my_channel1', 'my_channel2', 'my_channel3'],
channelGroups: ['my_channelGroup1', 'my_channelGroup2'],
withPresence: true,
triggerEvents: ['message', 'presence', 'status']
});

You are free to use events as you need them, can use one, two or three like this is shown above or you can also use the shortest way with triggerEvents:true. However if you are going to use presence event; the triggerEvents option must be accompanied with withPresence: true when it is being subscribed the channel.

There are two ways to use getMessage, getPresence, getStatus methods to catch messages, presences, and status in a callback. The first is to register a channel or channel group in individual way and the second is to register a set of channels using an array, in which this array can be included channels and channel group at the same time.

Listening to message event of a specific channel or channel group

pubnub.getMessage('my_channel1', function (msg) {
console.log(msg);
});

pubnub.getMessage('my_channelGroup', function (msg) {
console.log(msg);
});

pubnub.getMessage(['my_channel1', 'my_channel2', 'my_channelGroup'], function(msg) {
console.log(msg.message);
console.log(msg.channel);
});

Listening to presence event of a specific channel or channel group

pubnub.getPresence('my_channel1', function(pse) {
console.log(pse);
});

pubnub.getPresence('my_channelGroup', function(pse) {
console.log(pse);
});

pubnub.getPresence(['my_channel1', 'my_channel2', 'my_channelGroup'], function(pse) {
console.log(pse);
console.log(pse.subscribedChannel);
});

Listening to the global status for a channel or channel group

Via the status listener, you can receive different events such as when the network is online (PNNetworkUpCategory), when the SDK is connected to a set of channels (PNConnectedCategory), etc... See the list of events available in the API Reference

pubnub.getStatus('my_channel1', function(st) {
console.log(st);
});

pubnub.getStatus('my_channelGroup', function(st) {
console.log(st);
});

pubnub.getStatus(['my_channel1', 'my_channel2', 'my_channelGroup'], function(st) {
console.log(st);
});

Getting the stack of messages

The getMessage method is more than a mechanism for registering a channel, a set of channels or even a channel group to a callback that acts like a receptor to receive messages in real time when it is included the triggerEvents option at the moment of subscribing channels. The getMessage method will assign a stack for each register, this allows you to seamlessly bind a PubNub channel to your HTML or a local variable in your code.

Binding real time messages directly to the HTML

<ul *ngFor="let item of pubnub.getMessage('my_channel')">
<li>{{ item.message }}</li>
</ul>

Getting the stack of real time messages

var myStack1 = pubnub.getMessage('my_channel');

var myStack2 = pubnub.getMessage('my_channelGroup');

var myStack3 = pubnub.getMessage(['my_channel', 'my_channelGroup']);

Getting the stack of real time messages with using callback attached

var myStack1 = pubnub.getMessage('my_channel', function(msg) {
console.log(msg);
});

If you want to catch real time messages in your code and bind simultaneously these to your HTML. You will have to follow these steps.

Step 1: Register a callback to catch real time messages and get the stack
this.messages = pubnub.getMessage('my_channel', function(msg) {
console.log(msg);
});
Step 2: Using the stack gotten directly in your HTML
<ul *ngFor="let item of messages">
<li>{{ item.message }}</li>
</ul>

Cleaning and releasing the stack

pubnub.clean('my_channel1');

pubnub.clean('my_channelGroup');

pubnub.clean(['my_channel1', 'my_channel2']);

A very important point to describe here is the individuality of each stack. In the previous snippet of code we show three examples for cleaning a stack. If you can see the channel cleaned in the first line also appears in third line but when it executes the first line is not going to clean the data that it holds in the stack registered as a set till the third line is executed.

Sometime cleaning is good when you want to flush the data hold for the stack of messages but it is likely that for your app's lifecycle clean is not enough then you need release the stack and catch again in run time. Releasing a stack works like cleaning, in the same way you set up your channels you have to release them.

pubnub.release('my_channel1');

pubnub.release('my_channelGroup');

pubnub.release(['my_channel1', 'my_channel2']);

Getting the history with autoload

Autoload is extra parameter that you can pass at the moment of subscribing a channel, this allows to get the last messages stores in a fast and asynchronous way if your keys let to use this feature.

pubnub.subscribe({
channels: ['my_channel'],
triggerEvents: true,
withPresence: true,
autoload: 100
});

var messages = pubnub.getMessage('my_channel');

Copy and paste examples

In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

Init

Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform Access Manager administrative operations from this Angular2 instance.

Important

It is not a best practice to include the secretKey in client-side code for security reasons.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

Note

Set restore to true to allow catch-up on front-end applications.

Initializing the client

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

pubnub.init({
subscribeKey: 'YOUR SUB_KEY',
publishKey: 'YOUR PUB_KEY',
ssl: true
});

Listeners

Add Listeners

A listener lets you to catch up real time messages, get presence and status information if you do not want to use the getMessage, getPresence, getStatus methods. Remember add a listener before subscribing a channel.

pubnub.addListener({
status: function(st) {
if (st.category === "PNUnknownCategory") {
var newState = {
new: 'error'
};
pubnub.setState({
state: newState
},
function (status) {
console.log(st.errorData.message);
});
}
},
message: function(message) {
show all 22 lines

Time

Call time() to verify the client connectivity to the origin:

pubnub.time(function(status, response) {
if (status.error) {
console.log(status.error);
} else {
console.log(response.timetoken);
}
});

Subscribe

Subscribe (listen on) a channel:

pubnub.subscribe({
channels: ['my_channel'],
withPresence: true
});
Note

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Publish

Publish a message to a channel:

pubnub.publish(
{
message: {
such: 'object'
},
channel: 'ch1',
sendByPost: false, // true to send via POST
storeInHistory: false, //override default storage options
meta: {
"cool": "meta"
} // publish extra meta with the request
},
function (status, response) {
// handle status, response
}
show all 16 lines

Here Now

Get occupancy of who's here now on the channel by UUID:

Note

Requires you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.

pubnub.hereNow(
{
channels: ["my_channel"],
channelGroups : ["my_channelGroup"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
console.log(status);
console.log(response);
}
);

Presence

Subscribe to real-time Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:

Note

Requires you to enable the Presence add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.

pubnub.addListener({
presence: function(m) {
console.log(m);
},
message: function(message) {
console.log(message)
}
});

pubnub.subscribe({
channels: ["my_channel"],
withPresence: true
});
Note

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

History

Retrieve published messages from archival storage:

Note

Requires that the Message Persistence add-on is enabled for your key. How do I enable add-on features for my keys? - see https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

pubnub.history(
{
channel: 'my_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
function (status, response)
{
console.log(response);
}
);

Unsubscribe

Stop subscribing (listening) to a channel:

pubnub.unsubscribe({
channels : ['my_channel']
});
Note

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Last updated on