Angular2Angular2 Configuration API Reference for Realtime Apps

Angular2 V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.

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

  • Support: Available to use with Typescript or Javascript plain.
  • 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 recovery the history messages of your channel.
  • Multiple instance behavior: All instance are accessible throughout application via PubNub service.

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

npm install --save pubnub pubnub-angular2

You have to two ways for registering PubNubAngular in your list of providers in your Angular App and these are in: ngModules or ngComponents.

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 to use the same instance of PubNub inside itself and its Angular Components children. For more information about this we recommend to visit Depedency 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 in your ngComponents

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

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

  • Global dependencies for Angular2
  • Angular2
  • PubNub Javascript SDK
  • PubNub Angular2 SDK

With Javascript 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 lastest version of PubNub's Javascript SDK:
     
                    <script src="node_modules/pubnub/dist/web/pubnub.js"></script>
            
  4. Include PubNub's Angular2 SDK:
     
                    <script src="node_modules/pubnub-angular2/dist/pubnub-angular2.js"></script>
            

Your HTML page will have to include the same libraries described above but you have to load the Angular2 and 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 lastest version of PubNub's 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 and this will have to include next libraries inside the map attribute.

  • Rxjs
  • Angular2
  • PubNub Angular2 SDK

    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'
    }
    

You have to two ways for registering PubNub Angular2 SDK in your list of providers in your Angular App and these are in: Angular Modules or Components.

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.


    '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);
        });
    })(window.app || (window.app = {}));
    

    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 to use the same instance of PubNub inside itself and its Angular Components children. For more information about this we recommend to visit Dependency Injection and Hierarchical Dependency Injectors


    (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 = {}));
    

    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() {}
    }
    

Registering PubNubAngular within the provider list in an Angular Module or Component lets to inject an instance the PubNub in 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 will have to initialize the service including the PUB_KEY and SUB_KEY. It is important to know that this process has to be done once because this instance will be shared by all Angular Components within same scope according to its dependency model choose.


    (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 = {}));
    

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

To learn about PubNub JavaScript features refer to native PubNub JavaScript SDK manual. All methods of this SDK are wrapped with PubNubAngular.

Native PubNub JavaScript SDK provides instance creation using Pubnub.init(), which returns new instance with given credentials. In PubNub Angular2 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({}).


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

    anotherInstance.grant(
        {
            channels: ['my_channel'],
            authKeys: ['my_authkey'],
            read: true,
            write: false
        },
        function (status) {
            console.log(status);
        }
    );
    

    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!'},
            channel: 'my_channel'
        },
        (status, response) => {
            if (status.error) {
                console.log(status);
            } else {
                console.log('message Published w/ timetoken', response.timetoken);
            }
        }
    );

    anotherInstance.grant(
        {
            channels: ['my_channel'],
            authKeys: ['my_authkey'],
            read: true,
            write: false
        },
        (status) => {
            console.log(status);
        }
    );
    

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

                pubnub.publish(
                    {
                        message: {
                            such: 'Hello!'
                        },
                        channel: 'my_channel'
                    }, 
                    function (status, response) {
                        if (status.error) {
                            console.log(status);
                        } else {
                            console.log('message Published w/ timetoken', response.timetoken);
                        }
                    }
                );

                pubnub.getInstance('another').grant(
                    {
                        channels: ['my_channel'],
                        authKeys: ['my_authkey'],
                        read: true,
                        write: false
                    }, 
                    function (status) {
                        console.log(status);
                    }
                );
            }]
        });
    })(window.app || (window.app = {}));
    

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

            pubnub.getInstance('another').init({
                publishKey: 'ANOTHER PUB_KEY',
                subscribeKey: 'ANOTHER SUB_KEY'
            });

            pubnub.publish(
                {
                    message: {such: 'Hello!'},
                    channel: 'my_channel'
                },
                (status, response) => {
                    if (status.error) {
                        console.log(status);
                    } else {
                        console.log('message Published w/ timetoken', response.timetoken);
                    }
                }
            );

            pubnub.getInstance("another").grant(
                {
                    channels: ['my_channel'],
                    authKeys: ['my_authkey'],
                    read: true,
                    write: false
                }, (status) => {
                    console.log(status);
                }
            );
        }
    }
    

That's it, you are ready to start using PubNubAngular SDK.

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.
To Initialize Pubnub you can use the following method(s) in the Angular2 V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    subscribeKey String YesSpecifies the subscribeKey to be used for subscribing to a channel. This key can be specified at initialization or along with a subscribe().
    publishKey String OptionalSpecifies the publishKey to be used for publishing messages to a channel. This key can be specified at initialization or along with a publish().
    cipherKey String OptionalIf passed, will encrypt the payloads.
    authKey StringOptionalIf PAM enabled, this key will be used on all requests.
    logVerbosity Boolean Optionalfalselog HTTP information.
    uuid String Optional SDK generated random uuidUUID to use, if not passed, a random will be generated.
    ssl Boolean Optional

    true for v4.20.0 onwards,

    false before v4.20.0

    If set to true, requests will be made over HTTPS.
    origin String Optional ps.pndsn.comIf a custom domain is required, SDK accepts it here.
    presenceTimeout Number Optional 300

    How long the server will consider the client alive for presence.


    The value is in seconds.

    heartbeatInterval Number OptionalNot Set

    How often the client will announce itself to server.


    The value is in seconds.

    restore Boolean Optionalfalsetrue to allow catch up on the front-end applications.
    keepAliveBooleanOptional

    true for v4.18.0 onwards,

    false before v4.18.0

    If set to true, SDK will use the same TCP connection for each HTTP request, instead of opening a new one for each new request.
    keepAliveSettingsObjectOptional

    keepAliveMsecs: 1000


    freeSocketKeepAliveTimeout: 15000


    timeout: 30000


    maxSockets: Infinity


    maxFreeSockets: 256

    Set 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.
pubnub.init({
    subscribeKey: "YOUR SUB_KEY",
    publishKey: "YOUR PUB_KEY",
    ssl: true
});
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.
  1. pubnub.init({
        subscribeKey: 'YOUR SUB_KEY',
        publishKey: 'YOUR PUB_KEY',
        ssl: true
    });
  2. 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:
    pubnub.init({
        subscribeKey: "YOUR SUB_KEY"
    });
  3. Set a custom UUID to identify your users.
    pubnub.init({
        publishKey: 'YOUR PUB_KEY',
        subscribeKey: 'YOUR SUB_KEY',
        uuid: 'my_uuid'
    });
  4. 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.

    pubnub.init({
        subscribeKey: "YOUR SUB_KEY",
        publishKey: "YOUR PUB_KEY",
        ssl: true
    });
  5. Requires Access Manager add-on XRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
     

    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 PAM permissions, the API is initialized with the secretKey as in the following example:
    pubnub.init({
        subscribeKey: 'YOUR SUB_KEY',
        publishKey: 'YOUR PUB_KEY',
        secretKey: 'YOUR SECRET_KEY'
    });
    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secretKey to sign all PAM messages to the PubNub Network.
These functions are used to set/get a user ID on the fly.
To set/get UUID you can use the following method(s) in Angular2 V4 SDK
  1. ParameterTypeRequiredDescription
    uuid String YesUUID to set.
  2. This method doesn't take any arguments.

pubnub.setUUID('user 12345');
// return 'user 12345' according the previous example.
var uuid = pubnub.getUUID();
This function provides the capability to reset a user's auth Key.
Typically auth Key is specified during initialization for PubNub 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().
To Set Authentication Key you can use the following method(s) in the Angular2 V4 SDK
  1. ParameterTypeRequiredDescription
    key String YesAuth key to set.
pubnub.setAuthKey('my_authkey');
None.
Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
To set/get filters you can use the following methods.
  1. ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.
  2. This method doesn't take any arguments.

pubnub.setFilterExpression("such=wow");
pubnub.getFilterExpression();