PubNub AngularJS SDK 4.2.0

Unsupported SDK

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

Get Code

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

Get Code: CDN

Latest stable version

https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-.js

Latest stable minified version

https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.2.0.min.js

Get Code: Source

https://github.com/pubnub/pubnub-angular/tree/master/dist

Get Code: Bower

bower install --save pubnub pubnub-angular

Hello World

Pubnub Angular service is a wrapper for PubNub JavaScript SDK that adds a few extra features to simplify Angular integrations:

  • Multiple instance behavior: All instances are accessible throughout application via Pubnub service.
  • Events: Delegated methods accept the triggerEvents option which will broadcast certain callback as an AngularJS event.
  • A $pubnubChannel object that seamlessly binds a PubNub channel to a scope variable that gets updated with real-time data and allows you to interact with the channel through dedicated methods.
  • A $pubnubChannelGroup object that provides an easy-to-use interface for channel groups. It stores the incoming messages in containers split by the channel and exposes an interface to directly fetch messages by channel.

You can still use the native Pubnub JavaScript SDK if you feel this will be more suitable for your situation.

Integrating PubNub AngularJS SDK into Your App

Your HTML page will include 2 key libraries:

  • PubNub JavaScript SDK
  • PubNub JavaScript SDK AngularJS Service

To utilize this wrapper, include the scripts in the following order:

  1. Include AngularJS:

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  2. Include the latest version of PubNub's Javascript SDK

  3. Include PubNub's AngularJS SDK:

    <script src="<location-of-PubNub-SDK>/pubnub-angular-4.2.0.min.js"></script>

We presume your app is already AngularJS-enabled with an ng-app attribute or the equivalent:

<body ng-app="PubNubAngularApp">

Where PubNubAngularApp is the name of the AngularJS module containing your app.

We presume the code for the app lives in:

<script src="scripts/app.js"></script>

Inside app.js, add an AngularJS dependency on the PubNub AngularJS library (Pubnub.angular.service):

angular.module('PubNubAngularApp', ["pubnub.angular.service"])

This will make sure that the PubNub object is available to get injected into your controllers.

We presume the code for your controllers lives in:

<script src="scripts/controllers/main.js"></script>

The AngularJS Pubnub service is injected into the controller as follows:

.controller('MainCtrl', function($scope, Pubnub) { ... });

Differences in usage with native JavaScript SDK

To learn about Pubnub JavaScript features refer to native Pubnub JavaScript SDK manual. All methods of this SDK are wrapped with Pubnub AngularJS Service

Native Pubnub JavaScript SDK provides instance creation using Pubnub.init(), which returns new instance with given credentials. In Pubnub AngularJS SDK instances are hidden inside service and are accessible via instance getter. Methods of default instance are mapped directly to Pubnub service just like Pubnub.publish({...}). In most use cases usage of the only default Pubnub instance will be enough, but if you need multiple instances with different credentials, you should use Pubnub.getInstance(instanceName) getter. In this case publish method will looks like Pubnub.getInstance(instanceName).publish({}).

To summarize above let's check out the following 2 examples. Both of them performs the same job - creation of 2 Pubnub instances with different credentials. Publish method is invoked on the defaultInstance and grant method on anotherInstance

First example shows how to do that using 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. If you don't set the UUID, you won't be able to connect to PubNub.

var defaultInstance = new PubNub({
publishKey: 'your pub key',
subscribeKey: 'your sub key'
});

defaultInstance.publish(
{
message: {
such: 'Hello!'
},
channel: 'myChannel'
},
function (status, response) {
if (status.error) {
console.log(status)
show all 20 lines

Second example shows how to use Pubnub AngularJS SDK for this purposes:

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({
publishKey: 'your pub key',
subscribeKey: 'your sub key'
});

Pubnub.publish(
{
message: {
such: 'Hello!'
},
channel: 'myChannel'
},
function (status, response) {
if (status.error) {
console.log(status)
show all 20 lines

That's it - you're ready to start using the PubNub AngularJS SDK!

Hello World Example

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.

var helloWorldApp = angular.module('helloWorld', ['pubnub.angular.service']);

helloWorldApp.run(['Pubnub', function (Pubnub) {
Pubnub.init({
publishKey : 'demo',
subscribeKey : 'demo'
});
}]);

helloWorldApp.controller('HelloCtrl', ['$scope', 'Pubnub', function($scope, Pubnub) {
$scope.subscribe = function () {
Pubnub.subscribe({
channel: 'hello_world',
triggerEvents: ['message']
})
show all 36 lines

Events

Another key feature of this SDK is the ability to trigger method events in addition to passed in callbacks. By default events will not be triggered.

To enable all possible events for certain method, add triggerEvents: true option to the method arguments.

Triggering and listening to events for the subscribe method

With Javascript V4, you can trigger 3 different events (message, presence and status)

Triggering the events:

Pubnub.subscribe({
channels : [$scope.selectedChannel],
channelGroups: [$scope.selectedChannelGroup],
withPresence: true,
triggerEvents: ['message', 'presence', 'status']
});

You can also enable all possible events using triggerEvents: true.

Listening to a message event of a specific channel or channel group:

$rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
$scope.$apply(function () {
// add message to the messages list
$scope.chatMessages.unshift(envelope.message);
});
});

Listening to a presence event of a specific channel or channel group:

$rootScope.$on(Pubnub.getPresenceEventNameFor($scope.selectedChannel), function (ngEvent, pnEvent) {
// apply presence event (join|leave) on users list
handlePresenceEvent(pnEvent);
});

Listening to the global status events:

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

$rootScope.$on(Pubnub.getEventNameFor('subscribe', 'status'), function (ngEvent, status, response) {
if (status.category == 'PNConnectedCategory'){
console.log('successfully connected to channels', response);
}
});

Triggering and listening to events for the methods with callbacks

You have the possibility to trigger events for the methods with callbacks.

For the required callbacks, for ex. the callback called callback in the publish method, you should add it using one of the following ways:

  • callback function in method arguments
  • triggerEvents: ['callback']
  • triggerEvents: true (will trigger all the events of the method)

Triggering the events:

Method with callbacks as argument

Pubnub.publish(
{
channel: 'myChannel',
message: 'Hello!'
},
function(status, response){
console.log(response);
}
);

Method with events triggered

Pubnub.publish({
channel: 'myChannel',
message: 'Hello!',
triggerEvents: ['callback']
})

Listening to the events:

You can listen to the events that have been triggered using the Pubnub.getEventNameFor(...) helper from anywhere in your app. Params order in broadcasted events is the same as in native SDK methods, except that ngEvent object is prepended as the first param.

callback event will be triggered for both successful and unsuccesfull response:

$rootScope.$on(Pubnub.getEventNameFor('publish', 'callback'),
function (ngEvent, status, response) {
$scope.$apply(function () {
if (status.error){
$scope.statusSentSuccessfully = false;
} else {
$scope.statusSentSuccessfully = true;
}
})
}
);

The $pubnubChannel object

The $pubnubChannel object allows you to seamlessly bind a PubNub channel to a scope variable, which gets automatically updated when there is new real-time data published in that channel. It also lets you interact directly with the channel by calling dedicated methods available into the $scope variable bound to the $pubnubChannel object.

Getting started

Init Pubnub:

Pubnub.init({
publishKey: 'your pub key',
subscribeKey: 'your sub key'
});

Inject the $pubnubChannel service in a controller:

.controller('ScoresCtrl', function($scope, $pubnubChannel) { ... });

Bind the $pubnubChannel object to a scope variable providing a channel name and some optional parameters:

.controller('ScoresCtrl', function($scope, $pubnubChannel) {
$scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 50 })
});

Instantiating the $pubnubChannel is the only step needed to have a scope variable that reflects the real-time data from a channel. It subscribes to the channel for you, load initial data if needed and receive new real-time data automatically.

Display the $scope.scores variable in your view and you will see the data beeing loaded and updated when new data is received in that channel:

<body ng-app="app" ng-controller="ScoresCtrl">
<ul class="collection">
<li ng-repeat="score in scores">{{score.player}}<li>
</ul>
</body>

Optional config parameters

You can pass in some optional parameters in the config hash when instantiating the $pubnubChannel:

$scope.scores = $pubnubChannel('game-scores-channel', config)
  • autoload: 50 The number of messages (<100) we want to autoload from history, default: none.

  • autosubscribe: true Automatically subscribe to the channel, default: true

  • presence: false If autosubscribe is enabled, subscribe and trigger the presence events, default: false

  • instance: deluxeInstance The instance that will be used: default: {default PubNub instance}

Available methods

You can interact with the $pubnubChannel via dedicated methods:

.controller('ScoresCtrl', function($scope, $pubnubChannel) {
$scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 20 })
$scope.scores.$publish({player: 'John', result: 32}) // Publish a message in the game-scores-channel channel.
});

Here are some methods you can use:

  • $publish(messages): Publish a message into the channel, return a promise which is resolved when the data is published or rejected when there is an error.

  • $load(numberOfMessages): Load a number of messages from history into the array, return a promise resolved when the data is loaded and rejected if there is an error.

  • $allLoaded(): Return a boolean to indicate if all the messages from history have been loaded.

Wrapping the $pubnubChannel object in a Service

Instead of using the $pubnubChannel directly in a controller you can wrap it into a Service:

app.factory("Scores", ["$pubnubChannel",
function($pubnubChannel) {

var config = {
instance: 'myAnotherPubNubInstanceName', // By default, the default PubNub instance
autoload: 50 // Autoload the channel with 50 messages (should be < 100)
}
return $pubnubChannel('game-scores-channel', config);
}
]);

And use the Scores service in a controller:

app.controller("ScoresCtrl", ["$scope", "Scores", function($scope, Scores) {
$scope.messages = Scores();
]);

Extending the $pubnubChannel object

You can also extend the $pubnubChannel object using the $extend method in order to add or override methods:

angular.module('app').factory('Scores',
['$pubnubChannel',function ScoresService($pubnubChannel) {

// We create an extended $pubnubChannel channel object that add a additionnal sendScore method
// that publish a score with the name of the player preloaded.
var Scores = $pubnubChannel.$extend({
sendScore: function(score) {
return this.$publish({
player: 'John',
score: score
})
}
});

return Scores('game-scores-channel', {autoload: 30});
show all 18 lines

You can then use the Scores service in a controller:

app.controller("ScoresCtrl", ["$scope", "Scores", function($scope, Scores) {
$scope.scores = Scores();
$scope.scores.sendScore(34);
]);

The $pubnubChannelGroup object

The $pubnubChannelGroup provides an easy-to-use interface for channel groups. It stores the incoming messages in containers split by the channel and exposes an interface to directly fetch messages by channel using the $channel(channelName) method.

Getting started

Init Pubnub:

Pubnub.init({
publishKey: 'your pub key',
subscribeKey: 'your sub key'
});

Inject the $pubnubChannelGroup service in a controller:

.controller('ChatCtrl', function($scope, $pubnubChannelGroup) { ... });

Instantiate a $pubnubChannelGroup object and assign it to a scope variable providing a channel group name and some optional parameters.

.controller('ChatCtrl', function($scope, $pubnubChannelGroup) {
$scope.Conversations = $pubnubChannelGroup('conversations-channel-group')
// Fetch a $pubnubChannel from the Conversations $pubnubChannelGroup object
$scope.currentConversation = $scope.Conversations.$channel('conversation-178')
// $scope.messages is a $pubnubChannel, you can use any method available for a $pubnubChannel
$scope.currentConversation.$load(20)
});

Optional config parameters

You can pass in some optional parameters in the config hash when instantiating the $pubnubChannelGroup:

$scope.Conversation = $pubnubChannelGroup('conversations-channel-group', config)
  • autosubscribe: true Automatically subscribe to the channel, default: true

  • presence: false If autosubscribe is enabled, subscribe and trigger the presence events, default: false

  • instance: deluxeInstance The instance that will be used: default: {default PubNub instance}

  • channelExtension: {foo: function(){ return "bar"}} // Define or override methods for the channels returned when calling $channel on the $channelGroup object.

Methods Available

$channel(channel) Return a $pubnubChannel object which is containing the messages received via the channel group

Wrapping the $pubnubChannelGroup object in a Service

Instead of using the $pubnubChannelGroup directly in a controller you can wrap it into a Service:

app.factory("Conversations", ["$pubnubChannelGroup",
function($pubnubChannelGroup) {
return $pubnubChannelGroup('conversations-channel-group');
}
]);

And use the Conversation service in a controller:

app.controller("ChatCtrl", ["$scope", "Conversation", function($scope, Conversation) {
$scope.currentConversation = Conversations.$channel('conversation-13345');
]);

Extending channels of a $pubnubChannelGroup

When instanciating a $pubnubChannelGroup, you can pass in a channelExtension parameter that allows you to add or overrides methods for the $pubnubChannel objects that is returned when calling the $channel(channelName) method.

app.controller("ChatCtrl", ["$scope","$pubnubChannelGroup", function($scope, $pubnubChannelGroup) {

// We add a sendMessage methods that publish a message with an already defined payload.
var channelExtension = {
sendMessage: function(messageContent) {
return this.$publish({ content: messageContent, sender: "Tomomi" })
}
}
$scope.Conversations = $pubnubChannelGroup('channelGroup', {channelExtension: channelExtension});
$scope.currentConversation = $scope.Conversations.$channel('conversation-123')
// Sending a message via the extra method added to the channel.
$scope.currentConversation.sendMessage('Hello!')

]);

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 AngularJS V4 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.

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: "mySubscribeKey",
publishKey: "myPublishKey",
uuid: "myUniqueUUID",
ssl: true
})

Time

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

// At the tone Pubnub time will be...
Pubnub.time(function(status, response) {
if (status.error) {
// handle error if something went wrong based on the status object
} else {
console.log(response.timetoken);
}
});

Subscribe

Subscribe (listen on) a channel (it's async!):

// Subscribe to a channel
Pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNUnknownCategory") {
var newState = {
new: 'error'
};
Pubnub.setState(
{
state: newState
},
function (status) {
console.log(statusEvent.errorData.message)
}
);
show all 25 lines

Publish

Publish a message to a channel:

Pubnub.publish(
{
message: {
such: 'Hello from the PubNub Javascript SDK!'
},
channel: 'my_channel'
},
function (status, response) {
if (status.error) {
// handle error
console.log(status);
} else {
console.log("message Published w/ timetoken", response.timetoken);
}
}
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: ["ch1"],
channelGroups : ["cg1"],
includeUUIDs: true,
includeState: true
},
function (status, response) {
// handle status, 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
});

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: 'history_channel',
count: 100, // 100 is the default
stringifiedTimeToken: true // false is the default
},
function (status, response) {
// handle status, response
}
);

Unsubscribe

Stop subscribing (listening) to a channel.

// Unsubscribe from 'my_channel'

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