Configuration API for PubNub AngularJS SDK

AngularJS complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Initialization

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!

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.

Method(s)

To Initialize PubNub you can use the following method(s) in the AngularJS SDK:

init( {String subscribeKey, String publishKey, String cipherKey, String authKey, Boolean logVerbosity, String uuid, Boolean ssl, String origin, Number presenceTimeout, Number heartbeatInterval, Boolean restore, Boolean keepAlive, Object keepAliveSettings, Boolean suppressLeaveEvents, Number requestMessageCountThreshold, Boolean listenToBrowserNetworkEvents} )
ParameterTypeRequiredDefaultDescription
Operation ArgumentsHashYesA hash of arguments.
subscribeKeyStringYesSpecifies the subscribeKey to be used for subscribing to a channel. This key can be specified at initialization or along with a subscribe().
publishKeyStringOptionalSpecifies the publishKey to be used for publishing messages to a channel. This key can be specified at initialization or along with a publish().
cipherKeyStringOptionalIf passed, will encrypt the payloads.
authKeyStringOptionalIf Access Manager enabled, this key will be used on all requests.
logVerbosityBooleanOptionalfalselog HTTP information.
uuidStringYesUUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
sslBooleanOptionaltrue for v4.20.0 onwards,
false before v4.20.0
If set to true, requests will be made over HTTPS.
originStringOptionalps.pndsn.comIf a custom domain is required, SDK accepts it here.
presenceTimeoutNumberOptional300How long the server will consider the client alive for presence.The value is in seconds.
heartbeatIntervalNumberOptionalNot SetHow often the client will announce itself to server.The value is in seconds.
restoreBooleanOptionalfalsetrue to allow catch up on the front-end applications.
keepAliveBooleanOptionalfalseIf set to true, SDK will use the same TCP connection for each HTTP request, instead of opening a new one for each new request.
keepAliveSettingsObjectOptionalkeepAliveMsecs: 1000 freeSocketKeepAliveTimeout: 15000 timeout: 30000 maxSockets: Infinity maxFreeSockets: 256Set a custom parameters for setting your connection keepAlive if this is set to true.keepAliveMsecs: (Number) how often to send TCP KeepAlive packets over sockets.freeSocketKeepAliveTimeout: (Number) sets the free socket to timeout after freeSocketKeepAliveTimeout milliseconds of inactivity on the free socket.timeout: (Number) sets the working socket to timeout after timeout milliseconds of inactivity on the working socket.maxSockets: (Number) maximum number of sockets to allow per host.maxFreeSockets: (Number) maximum number of sockets to leave open in a free state.
suppressLeaveEventsBooleanOptionalfalseWhen true the SDK doesn't send out the leave requests.
requestMessageCountThresholdNumberOptional100PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above of requestMessageCountThreshold.
listenToBrowserNetworkEventsBooleanOptionalfalseIf the browser fails to detect the network changes from WiFi to LAN and vice versa or you get reconnection issues, set the flag to false. This allows the SDK reconnection logic to take over.

Basic Usage

Initialize the PubNub client API:

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: "my_subkey",
publishKey: "my_pubkey",
ssl: true
});

Returns

It returns the PubNub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.

Other Examples

  1. Initialize 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: "mySubscribeKey",
    publishKey: "myPublishKey",
    uuid: "myUniqueUUID",
    ssl: true
    })
  2. Initialization for a Read-Only client:

    In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when 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: 'my_subkey'
    })
  3. Use a custom UUID

    Set a custom UUID to identify your users.

    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: 'myPublishKey',
    subscribeKey: 'mySubscribeKey',
    uuid: 'myUniqueUUID'
    })
  4. Initializing with SSL Enabled:

    This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

    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: "my_subkey",
    publishKey: "my_pubkey",
    ssl: true
    });
  5. Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
    https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

    Note

    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secretKey be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure environments such as Node.js application or other server-side platforms.

    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.

    For applications that will administer Access Manager permissions, the API is initialized with the secretKey as in the following 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.

    Pubnub.init({
    subscribeKey: 'my_subkey',
    publishKey: 'my_pubkey',
    secretKey: 'my_secretkey'
    });

    Now that the pubnub object is instantiated the client will be able to access the Access Manager functions. The pubnub object will use the secretKey to sign all Access Manager messages to the PubNub Network.

UUID

These functions are used to set/get a user ID on the fly.

Method(s)

To set/get UUID you can use the following method(s) in AngularJS SDK:

  1. Pubnub.setUUID(string)
    ParameterTypeRequiredDescription
    uuidStringYesUUID to set.
  2. Pubnub.getUUID()

    This method doesn't take any arguments.

  3. PubNub.generateUUID()

    This method doesn't take any arguments.

Basic Usage

Set UUID:

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.setUUID("myUniqueUUID")

Get UUID:

Pubnub.getUUID();

Generate UUID:

PubNub.generateUUID();

Other Examples

  1. Creating a function to subscribe to a channel with a unique name:

    var channel = PubNub.generateUUID();

    Pubnub.subscribe({
    channels: [channel]
    })
  2. Initializing with a custom uuid:

    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 newUUID = PubNub.generateUUID();

    Pubnub.init({
    uuid: newUUID,
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    secretKey: "secretKey"
    });
  3. Creating a unique auth Key for Access Manager on initialization:

    var randomAuthKey = PubNub.generateUUID();

    Pubnub.init({
    authKey: randomAuthKey,
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    secretKey: "secretKey"
    });

Authentication Key

This function provides the capability to reset a user's auth Key.

Typically auth Key is specified during initialization for Access Manager enabled applications. In the event that auth Key has expired or a new auth Key is issued to the client from a Security Authority, the new auth Key can be sent using setAuthKey().

Property

To Set Authentication Key you can use the following method(s) in the AngularJS SDK:

  1. Pubnub.setAuthKey(string)
    ParameterTypeRequiredDescription
    keyStringYesAuth key to set.

Basic Usage

Pubnub.setAuthKey('my_new_authkey')

Returns

None.

Filter Expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set or get message filters, you can use the following method.

Method(s)

  1. Pubnub.setFilterExpression(String filterExpression)
    ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.
  2. Pubnub.getFilterExpression()

    This method doesn't take any arguments.

Basic Usage

Set Filter Expression

Pubnub.setFilterExpression("such=wow");

Get Filter Expression

Pubnub.getFilterExpression();
Last updated on