Feedback

AngularJSPubNub AngularJS V4 SDK 4.0.2

 

These docs are for PubNub 4.0 for AngularJS which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for AngularJS.

If you have questions about the PubNub for JavaScript SDK, please contact us at support@pubnub.com.

Latest stable minified version

bower install --save pubnub pubnub-angular

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 realtime 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.

Your HTML page will include 2 key libraries:

  • PubNub JavaScript SDK
  • PubNub JavaScript SDK AngularJS Service
  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="//cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.0.2.min.js"></script>
    
<body ng-app="PubNubAngularApp">

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

<script src="scripts/app.js"></script>
angular.module('PubNubAngularApp', ["pubnub.angular.service"])

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

<script src="scripts/controllers/main.js"></script>
.controller('MainCtrl', function($scope, Pubnub) { ... });

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.

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)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);
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)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);

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

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']
        })
    }
}]);
 
helloWorldApp.controller('WorldCtrl', function($scope, $rootScope, Pubnub) {
    $rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
        $scope.$apply(function () {
            // add message to the messages list
            $scope.chatMessages.unshift(envelope.message);
        });
    });
 
    $rootScope.$on(Pubnub.getEventNameFor('publish', 'callback'), function (ngEvent, status, response) {
        $scope.$apply(function () {
            if (status.error){
               $scope.statusSentSuccessfully = false;
            } else {
               $scope.statusSentSuccessfully = true;
            }
         })
    });
});

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.

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

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

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

    $rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
        $scope.$apply(function () {
            // add message to the messages list
            $scope.chatMessages.unshift(envelope.message);
        });
    });
    
    $rootScope.$on(Pubnub.getPresenceEventNameFor($scope.selectedChannel), function (ngEvent, pnEvent) {
        // apply presence event (join|leave) on users list
        handlePresenceEvent(pnEvent);
    });
    

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);
        }
    });
    

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)
    Pubnub.publish(
        {
            channel: 'myChannel',
            message: 'Hello!'
        }, 
        function(status, response){
            console.log(response);
        }
    );
    
    Pubnub.publish({
        channel: 'myChannel',
        message: 'Hello!',
        triggerEvents: ['callback']
    })
    

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 allows you to seamlessly bind a PubNub channel to a scope variable, which gets automatically updated when there is new realtime 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.

    Pubnub.init({
        publishKey: 'your pub key',
        subscribeKey: 'your sub key'
    });
    
    .controller('ScoresCtrl', function($scope, $pubnubChannel) { ... });
    
    .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 realtime data from a channel. It subscribes to the channel for you, load initial data if needed and receive new realtime 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>
    

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}

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.

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();
    ]);
    

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});

        }]
    );
    

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

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

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.

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

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');
    ]);
    

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!')

    ]);
    
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
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 PAM administrative operations from this AngularJS V4 instance.
 

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.

 
Set restore as true to allow catch up on the front-end applications.
Pubnub.init({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	ssl: true
})
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 (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)
                }
            );
        }
    },
    message: function(message) {
        console.log(message)
    }
})

Pubnub.subscribe({
    channels: ['my_channel']
});
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)
        }
    }
);
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
Pubnub.hereNow(
    {
        channels: ["ch1"], 
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true 
    },
    function (status, response) {
        // handle status, response
    }
);
Subscribe to realtime 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:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
Pubnub.addListener({
    presence: function(m){
        console.log(m)
    },
    message: function(message) {
        console.log(message)
    }
})
 
Pubnub.subscribe({
    channels: ["my_channel"],
    withPresence: true
});
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
Pubnub.history(
    {
        channel: 'history_channel',
        reverse: false, // false is the default
        count: 100, // 100 is the default
        stringifiedTimeToken: true // false is the default
    },
    function (status, response) {
        // handle status, response
    }
);
Stop subscribing (listening) to a channel.
// Unsubscribe from 'my_channel'

Pubnub.unsubscribe({
	channels : ['my_channel']
});
Check out PubNub's other JavaScript-based SDKs, such as JavaScript V4, Node.js V4.