---
source_url: https://www.pubnub.com/docs/sdks/angular2
title: Angular2 API & SDK Docs 1.3.2
updated_at: 2026-06-12T11:24:33.274Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Angular2 API & SDK Docs 1.3.2

:::warning Unsupported SDK
PubNub no longer supports this SDK.
For new Angular projects, use the [JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript) directly. The JavaScript SDK is fully compatible with modern Angular and can be easily integrated using Angular services and dependency injection. For chat applications, consider the [Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk) which provides higher-level abstractions.
Legacy contributions are [welcome on GitHub](https://github.com/pubnub/pubnub-angular2).
:::

## Get code

[https://github.com/pubnub/pubnub-angular2/releases](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](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](https://cdn.pubnub.com/sdk/pubnub-angular2/pubnub-angular2.1.3.2.min.js)

## Get code: source

[https://github.com/pubnub/pubnub-angular2](https://github.com/pubnub/pubnub-angular2)

## Get code: NPM

```bash
npm install --save pubnub pubnub-angular2
```

## Get code: bower

:::warning Bower Deprecated
Bower has been deprecated since 2017. Use the npm installation method above instead. For new projects, consider using the [JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript) directly with modern Angular applications.
:::

```bash
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

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

```javascript
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](https://angular.io/guide/dependency-injection) and [Hierarchical Dependency Injectors](https://angular.io/guide/hierarchical-dependency-injection)

```javascript
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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```javascript
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: 1<script src="node_modules/core-js/client/shim.min.js"></script>2<script src="node_modules/zone.js/dist/zone.js"></script>3<script src="node_modules/reflect-metadata/Reflect.js"></script>4<script src="node_modules/rxjs/bundles/Rx.js"></script>
2. Include Angular2: 1<script src="node_modules/@angular/core/bundles/core.umd.js"></script>2<script src="node_modules/@angular/common/bundles/common.umd.js"></script>3<script src="node_modules/@angular/compiler/bundles/compiler.umd.js"></script>4<script src="node_modules/@angular/platform-browser/bundles/platform-browser.umd.js"></script>5<script src="node_modules/@angular/forms/bundles/forms.umd.js"></script>6<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: 1<script src="node_modules/pubnub/dist/web/pubnub.js"></script>
4. Include the PubNub Angular2 SDK: 1<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: 1<script src="node_modules/core-js/client/shim.min.js"></script>2<script src="node_modules/zone.js/dist/zone.js"></script>3<script src="node_modules/reflect-metadata/Reflect.js"></script>4<script src="node_modules/rxjs/bundles/Rx.js"></script>
2. Include the latest version of the PubNub JavaScript SDK: 1<script src="node_modules/pubnub/dist/web/pubnub.js"></script>
3. Include and load libraries from systemjs: 1<script src="node_modules/systemjs/dist/system.src.js"></script>2<script src="systemjs.config.js"></script>3<script>4 System.import('app').catch(function(err){5 console.error(err);6 });7</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:

```javascript
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

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

##### Registering inside an Angular module using TypeScript

```javascript
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](https://angular.io/guide/dependency-injection) and [Hierarchical Dependency Injectors](https://angular.io/guide/hierarchical-dependency-injection)

##### Registering inside an Angular component using JavaScript

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

```javascript
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](https://angular.io/guide/hierarchical-dependency-injection) 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```javascript
(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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```javascript
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](https://www.pubnub.com/docs/sdks/javascript) 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

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

##### 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

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

#### 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

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

##### 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)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```javascript
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're ready to start using the **PubNub Angular SDK**.

## Hello World example

### Hello World example using JavaScript

```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;
            setInterval(function () {
                var hw = 'Hello World, ' + Date.now();
                    self.pubnub.publish({channel: self.channel, message: hw});
            }, 1000);
        }
    });
})(window.app || (window.app = {}));
```

### Hello World example using TypeScript

```javascript
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;
        this.pubnub.init({
            publishKey: 'YOUR PUB_KEY',
            subscribeKey: 'YOUR SUB_KEY'
        });
        this.pubnub.subscribe({
            channels: [this.channel],
            triggerEvents: ['message']
        });
    }
    ngOnInit() {
        setInterval(() => {
            let hw = 'Hello World, ' + Date.now();
            this.pubnub.publish({
                channel: this.channel, message: hw
            });
        }, 1000);
    }
}
```

## 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:

```javascript
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

```javascript
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

```javascript
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](https://www.pubnub.com/docs/sdks/angular/api-reference/publish-and-subscribe#listeners)

```javascript
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

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

#### Getting the stack of real time messages

```javascript
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

```javascript
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

```javascript
this.messages = pubnub.getMessage('my_channel', function(msg) {
    console.log(msg);
});
```

##### Step 2: Using the stack gotten directly in your HTML

```html
<ul *ngFor="let item of messages">
    <li>{{ item.message }}</li>
</ul>
```

#### Cleaning and releasing the stack

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

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

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

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

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

```javascript
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) {
        console.log(message);
    }
});

pubnub.subscribe({
    channels: ['my_channel']
});
```

### Subscribe

Subscribe (listen on) a channel:

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

:::note
The response of the call is handled by adding a Listener. Please see the [Listeners section](#listeners) for more details. Listeners should be added before calling the method.
:::

### Publish

Publish a message to a channel:

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

### 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?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
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?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
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](#listeners) 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-](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-)
:::

```javascript
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:

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

:::note
The response of the call is handled by adding a Listener. Please see the [Listeners section](#listeners) for more details. Listeners should be added before calling the method.
:::